<?php

class Bot
{
   var $HTMLTags;
   var $zyAuthHash;//fortunes
   var $flashRevision;
   var $zySnuid;
   var $zyUid;
   var $zySnid;
   var $zySig;
   var $zySig2;

   var $sequense;
   var $usern;
   var $session;

   var $pm;
   var $ld;

   var $level;
   var $gold;
   var $cash;
   var $xp;
   var $energy;
   var $energyMax;
   var $CityName;//addded by phreaker 26-02-2011
   var $SocialLevel;//addded by phreaker 26-02-2011

   var $Goods;
   var $MaxGoods;//added by rlff38
   var $PremiumGoods;//addded by phreaker 27-02-2011
   var $PremiumGoodsMax;//added by rlff38
   
   var $Bandit;//addded by phreaker 15-03-2011
   var $BanditCaptured;//addded by phreaker 15-03-2011
   var $BanditInfo;//addded by phreaker 15-03-2011
   //********************edit by sowijo_kaskuser******************
   var $arBanditQueue;
   var $arPoliceOfficer;
   var $copsAndBandits;
   //*************************************************************
   var $banditlist;//added by Tonycell
   var $policelvl7;//added by Tonycell

   var $BanditCapturedDT;
   var $arBanditQueueDT;
   var $arPoliceOfficerDT; 
   var $banditlistDT;
   
   //added by Tonycell
   var $dogCaptured;
   var $dogQueue;
   var $dogOfficers;
   var $dogList;//doggie list from XML
  
   var $EternalFountain;//added by Tonycell 10.10.2011

   var $fobjects; // Main World Objects
   var $dt_fobjects; // Downtown World Objects
   var $currentWorld; // Current World Loaded
   var $neighbors;

   var $error_msg;
   var $hooks;

   var $traymsg;
   var $xmlsOb;
   var $firstrun;

   var $dooberCoins;
   var $dooberXps;
   var $dooberEnergys;
   var $dooberItems;
   var $dooberItem;
   var $CheckDoober;

   var $xmlConfig;
   var $streakBonusCheck;// added by 12Christiaan to be switch on / off streakBonus
   // See function streakBonusCheck

   var $train;// added by pjhkaka

   var $statistics;//fix by Tonycell
   
   //Albertos
   var $arCars;
   var $arQuests;

   // ==========================================================================
   function Bot()
   {
   }

   function irc($code)
   {
      switch($code)
      {
         case 'u': return chr(31);
         case 'b': return chr(2);
         case 'cc': return chr(3);
         case 'ff': return chr(6);
         case 'c': return chr(15);
      }
   }
   // ==========================================================================
   // Added by Tony cell
   // * Fix for enqueueTime & stamp
   // * some functions may require this in order to work
   // ==========================================================================
   function GetTimers(&$stamp, &$enqueueTime, &$clientEnqueueTime)
   {
      list($l1, $l2) = explode(" ", microtime());
      $b1 = bcmul($l2, '1000.0', 3);
      $b2 = bcmul($l1, '1000.0', 3);
      $stamp = bcadd($b1, $b2, 0);

      $s1 = strval(rand(0, 1000));
      $b3 = bcsub($stamp, $s1, 3);
      $enqueueTime = (float)bcdiv($b3, '1000.0', 3);
      $clientEnqueueTime = (float)bcdiv($b3, '1000.0', 0);
   }
   function GetTimersNew(&$stamp, &$NEWenqueueTime, &$NEWclientEnqueueTime, &$number)
   {
      list($l1, $l2) = explode(" ", microtime());
      $b1 = bcmul($l2, '1000.0', 3);
      $b2 = bcmul($l1, '1000.0', 3);
      $stamp = bcadd($b1, $b2, 0);

      $s1 = strval(rand(0, 1000));
      $b3 = bcsub($stamp, $s1, 3);
      $enqueueTime = (float)bcdiv($b3, '1000.0', 3);
      $clientEnqueueTime = (float)bcdiv($b3, '1000.0', 0);

      $NEWenqueueTime = bcadd($enqueueTime, (string)($number / 10), 3);
      $NEWclientEnqueueTime = bcadd($clientEnqueueTime, (string)($number / 10), 0);
   }
   function GetBanditsFromXML($type)
   {
      $fn = 'tmp_dir\gameSettings.xml';
      $fl = fopen($fn, 'r');
      $s = fread($fl, filesize($fn));
      fclose($fl);
      $xml1 = simplexml_load_string($s);
      if($type == 1)        {$bandits = $xml1->preyGroups->preyGroup[0];}//bandits
      else
         if($type == 2)           {$bandits = $xml1->preyGroups->preyGroup[1];}//doggies
		 else
            if($type == 3)           {$bandits = $xml1->preyGroups->preyGroup[2];}//banditsDT

      $s = array();
      if(isset($bandits->preys->prey))
         //foreach($banditlist->bandit as $key=>$item)
         foreach($bandits->preys->prey as $key=>$item)
         {
            $id = strval($item['id']);
            $cops = strval($item->modes->mode[0]['huntersRequired']);
            //$s[] = $id;
            $s[$id] = $cops;
         }
      unset($xml1);
      return $s;
   }
   // ==========================================================================
   function Init()
   {

      $this->ld = new LocalData();//moved to here

      $this->CheckDoober = false;

      //before - [date_default_timezone_set($this->GetParamByName("sTimeZone"));]
      //after -
      date_default_timezone_set('Europe/London');

      $this->SendMsg($this->irc('ff') . '13' . chr(232) . $this->irc('ff') . 'Bot Init [Phase 1]');

      define('AMFPHP_BASE', 'amfphp/core/');
      require_once(AMFPHP_BASE . "shared/util/CharsetHandler.php");
      require_once(AMFPHP_BASE . "amf/util/AMFObject.php");
      require_once(AMFPHP_BASE . "shared/util/CompatPhp5.php");
      require_once(AMFPHP_BASE . "shared/util/MessageBody.php");
      require_once(AMFPHP_BASE . "shared/app/Constants.php");
      require_once(AMFPHP_BASE . "shared/app/Globals.php");
      require_once(AMFPHP_BASE . "amf/io/AMFDeserializer.php");
      require_once(AMFPHP_BASE . "amf/io/AMFSerializer.php");

      global $headers_file, $amfbin_file;
      if((file_exists($amfbin_file) == false) or (file_exists($headers_file) == false))
      {
         $this->SendMsg('Cannot find MainRequest.bin or Headers.bin');
         $this->SendMsg('If running on windows 7, please run the bot as administrator');
         exit;
      }

      try
      {
         $f = fopen($amfbin_file, 'r');
         $size = filesize($amfbin_file);
         $amf = new AMFObject(fread($f, $size));
         fclose($f);
      }catch(Exception$e)
      {
         $this->SendMsg($e->getMessage());
         exit;
      }

      $deserializer = new AMFDeserializer($amf->rawData);
      $deserializer->deserialize($amf);

      $bod = new MessageBody();
      $bod = $amf->_bodys[0];

      $this->zyAuthHash = trim($bod->_value[0]['zyAuthHash']);
      $this->flashRevision = trim($bod->_value[0]['flashRevision']);

      /*if(isset($this->zySig2))
      {
         $this->SendMsg("zySig updated ");
         $this->zySig = $this->zySig2;
      }
      else
      {
         $this->zySig = trim($bod->_value['0']['zySig']);
      }*/

      $this->zySig = trim($bod->_value[0]['zySig']);
      $this->zySnid = trim($bod->_value[0]['zySnid']);
      //$this->zyUid=trim($bod->_value['0']['zyUid']);				   2011-02-17 no longer in this file.
      //  zyUid = Z uid
      //$this->zySnuid=trim($bod->_value['0']['zySnuid']);			   2011-02-17 no longer in this file.
      //   zySnuid used for DB = facebook id

      $this->usern = trim($bod->_value[1][0]['params'][0]);
      $this->session = trim($bod->_value[1][0]['params'][1]);

      $fh = file($headers_file);
      $this->url = trim($fh[0]);
      unset($fh[0]);
      foreach($fh as $value)
      {
         $pos = strpos($value, ':');
         $name = trim(substr($value, 0, $pos));
         $val = trim(substr($value, $pos + 1, strlen($value)));
         $headers[$name] = $val;
      }

      $this->host = $headers['Host'];
      $this->x_flash_version = $headers['x-flash-version'];
      $this->headers["Accept"] = $headers['Accept'];
      $this->headers["Accept-Language"] = $headers['Accept-Language'];
      $this->headers["Referer"] = $headers['Referer'];
      $this->headers["x-flash-version"] = $headers['x-flash-version'];
      $this->headers["Content-Type"] = $headers['Content-Type'];
      $this->headers["Accept-Encoding"] = "deflate";
      $this->headers["User-Agent"] = $headers['User-Agent'];
      $this->headers["Host"] = $headers['Host'];
      if(isset($headers['Connection']))
      {
         $this->headers["Connection"] = $headers['Connection'];
      }
      if(isset($headers['Proxy-Connection']))
      {
         $this->headers["Proxy-Connection"] = $headers['Proxy-Connection'];
      }
      if(isset($headers['Pragma']))
      {
         $this->headers["Pragma"] = $headers['Pragma'];
      }
      if(isset($headers['Cache-Control']))
      {
         $this->headers["Cache-Control"] = $headers['Cache-Control'];
      }
      $this->headers["Cookie"] = $headers['Cookie'];

      $this->pm = new PluginManager();
      $this->pm->GetConfiguration();

   }

   // ==========================================================================
   function Init2()
   {
      // second phase of the init
      // after the reload.

      //$this->SendMsg('Bot Init 2');
      $this->SendMsg($this->irc('ff') . '13' . chr(232) . $this->irc('ff') . 'Bot Init [Phase 2]');

      $this->ld->ConnectTo($this->zySnuid);

      global $headers_file, $amfbin_file;
      $this->firstrun = false;
      if($amfbin_file != 'tmp_dir\\' . $this->zySnuid . '_amf.bin')
      {
         echo "Deleting old BIN files \n";
         if(file_exists('tmp_dir\\' . $this->zySnuid . '_amf.bin'))
         {
            unlink('tmp_dir\\' . $this->zySnuid . '_amf.bin');
            unlink('tmp_dir\\' . $this->zySnuid . '_headers.bin');
         }
         $this->firstrun = true;
         SendApi('BotApi.SetUserId=' . $this->zySnuid);
      }

      $this->xmlConfig = new xmlConfig();
      $ConfigArray = array();
      $ConfigArray = $this->GetAmfHeader();
      //$ConfigArray["Cookie"] =$headers['Cookie'];
      $ConfigArray["Cookie"] = $this->headers["Cookie"];
      //$ConfigArray["Referer"] =$headers['Referer'];
      $ConfigArray["Referer"] = $this->headers["Referer"];
      //$ConfigArray["UserAgent"] =$headers['User-Agent'];
      $ConfigArray["UserAgent"] = $this->headers["User-Agent"];
      $ConfigFile = $this->zySnuid . '__Zy.xml';
      $this->xmlConfig->writeXml($ConfigFile, $ConfigArray);

   }

   // ==========================================================================
   function IncludeAllHooks()
   {
      foreach($this->pm->plugins as $plugin)
      {
         if(($plugin['active'] == '1') && (file_exists($plugin['hooks']))) //fix by AnonymouS [24/8/2011] - loading only active plugins
         {
            include($plugin['hooks']);
         }
      }
   }

   // ==========================================================================
   function ShowReportMsgInTray()
   {
      if(count($this->statistics) > 0)
      {
         foreach($this->statistics as $key=>$value)
         {
            $this->traymsg[] = $key . " = " . sizeof($value);
         }
      }

      if(isset($this->traymsg))
      {
         if(sizeof($this->traymsg) > 0)
         {
            $this->SendMsg("");

            foreach($this->traymsg as $msg)
            {
               $tmp = $tmp . $msg . "\n";
               $this->SendMsg($msg);
            }
            if(strlen($tmp) > 0)
            {
               SendApi('BotApi.ShowTrayMsg=' . $tmp);
            }
         }
      }
   }

   // ==========================================================================
   function AddHook($hook, $fname)
   {
      $this->hooks[$hook][] = $fname;
   }

   // ==========================================================================
   function Hook($hook)
   {
      if(isset($this->hooks[$hook]))
      {
         foreach($this->hooks[$hook] as $function)
         {
            if(function_exists($function))
            {
               call_user_func($function, $this);
            }
         }
      }
   }

   // ==========================================================================
   function GetAmfHeader()
   {
      $arr['flashRevision'] = (int)$this->flashRevision;
      $arr['zyAuthHash'] = $this->zyAuthHash;//fortunes
      $arr['zySig'] = $this->zySig;
      $arr['zySnid'] = (int)$this->zySnid;
      //$arr['zyUid'] = $this->zyUid;				 // no longer needed 2011-2-17 Z update
      //$arr['zySnuid'] = $this->zySnuid;			 // no longer needed 2011-2-17 Z update
      global $Zy;
      $Zy = $arr;
      return $arr;

   }
   // ==========================================================================
   function CheckEnergy()
   {
      // inventory stuff  Energy
      $this->SendMsg('[Energy] Checking the inventory for Energy');
      $tmp = 0;

      if(is_array($this->Inventory['items']))
      {
         foreach($this->Inventory['items'] as $item=>$n)
         {
            $ItemName = $item;//$n['Item'];
            $ItemNumber = $n;//['Number'];

            // Let's do some checks to see if settings are defined.
            if(strpos($ItemName, "nergy") == 0)              {continue;}// skipping item = not energy

            // we have more than we need to keep.
            $this->SendMsg("[Energy] $ItemName ($ItemNumber) found.");
            while($ItemNumber > 0)
            {
               $this->SendMsg("[Energy] Preforming action on $ItemName have: $ItemNumber");
               $ItemNumber--;
               $this->BuyEnergy("UserService.buyEnergy", $ItemName);
               $this->ReloadConfig();
               $tmp++;

               if(isset($this->error_msg)) //for "Sequence OOS" errors
               {
                  $this->ReloadConfig();
               }

               if($this->energy >= 30)
               {
                  $this->SendMsg("[Energy] Maximum energy number reached");
                  return $tmp;
               }
            }
         }
      }
      if($tmp == 0)
         $this->SendMsg('[Energy] No energy found in you inventory.');
      return $tmp;
   }
   // ==========================================================================
   /*
    * Loads $world as current world
    * Sets $bot->currentWorld
	* Returns worlds objects
	*/
	function LoadWorldObjects($world)
	{
		if ($world == "world_main") $msg = "Main World"; else $msg = "Downtown World";
		$this->SendMsg($this->irc('b') . 'Loading ' . $msg);

		unset($this->error_msg);
		$amf = new AMFObject("");
		$amf->_bodys[0] = new MessageBody();
		$amf->_bodys[0]->_value[0] = $this->GetAmfHeader();
		$amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
		$amf->_bodys[0]->responseURI = '';
		$this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
		$amf->_bodys[0]->_value[1][0]['transaction']['mustGoFirstInBatch'] = true;
		$amf->_bodys[0]->_value[1][0]['transaction']['mustGoLastInBatch'] = true;
		$amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;
		$amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);
		$amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);
		$amf->_bodys[0]->_value[1][0]['functionName'] = "WorldService.loadWorld";
		$amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
		$amf->_bodys[0]->_value[1][0]['params'][0] = $this->zySnuid;
		$amf->_bodys[0]->_value[1][0]['params'][1] = $world; // 'world_downtown' 'world_main'
		$amf->_bodys[0]->_value[2] = 0;

		$serializer = new AMFSerializer();
		$result = $serializer->serialize($amf);
		$x = $this->SendRequest($result);
		$x = $this->Deserialize($x);
		$this->CheckServerError($x);
		$bod = $x->_bodys[0];
		//$msg = $bod->_value['data'][0]['data']['worldName'];
		//$this->SendMsg($this->irc('cc') . '2(' . $msg . ') ');
		
		$this->currentWorld = $world;

		return $bod->_value['data'][0]['data']['world']['objects'];
	}

	// ==========================================================================
   function ReloadConfig()
   {
      $this->SendMsg($this->irc('b') . 'Loading configuration...');

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '/1';

      //Added by Tonycell
      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.initUser";
      $amf->_bodys[0]->_value[1][0]['sequence'] = 1;
      $amf->_bodys[0]->_value[1][0]['params'][0] = $this->usern;
      $amf->_bodys[0]->_value[1][0]['params'][1] = $this->session;


      $amf->_bodys[0]->_value[1][1]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][1]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][1]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][1]['functionName'] = "UserService.initNeighbors";
      $amf->_bodys[0]->_value[1][1]['sequence'] = 2;
      $amf->_bodys[0]->_value[1][1]['params'] = array();
      $amf->_bodys[0]->_value[2] = 0;
      //

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $tmp = 'tmp_dir\reload.amf';
      if(file_exists($tmp)) unlink($tmp); //delete the file if exists
      $f = fopen($tmp, 'x');
      fwrite($f,$result);
      fclose($f);


      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      //$amf = new AMFObject($x);
      //$deserializer = new AMFDeserializer($amf->rawData);
      //$deserializer->deserialize($amf);
      //$bod = new MessageBody();
      //$bod = $amf->_bodys[0];
      $bod = $x->_bodys[0];
      $this->cfg = $bod;
      $this->sequense = 2;

      $this->zyUid = $bod->_value['data'][0]['data']['userInfo']['id'];//addded by phreaker 2011-2-17 Z update
      $this->zySnuid = $this->zyUid;// for now we use the Z id, not the facebook id.
      $this->CityName = $bod->_value['data'][0]['data']['userInfo']['worldName'];//addded by phreaker 26-02-2011
      $this->SocialLevel = $bod->_value['data'][0]['data']['userInfo']['player']['socialLevel'];//addded by phreaker 26-02-2011

      $this->Bandit = $bod->_value['data'][0]['data']['featureData']['copsNBandits']['banditQueue'][0];//addded by phreaker 15-03-2011
      $this->BanditCaptured = $bod->_value['data'][0]['data']['featureData']['copsNBandits']['numBanditsCaptured'];//addded by phreaker 15-03-2011
      $this->BanditInfo = $bod->_value['data'][0]['data']['copsAndBandits']['bandits'][0];//addded by phreaker 15-03-2011

      //************************edit by sowijo_kaskuser***************************
      //bandit queue
      $banditqueue = array();
      $banditqueue = $bod->_value['data'][0]['data']['featureData']['copsNBandits']['banditQueue'];
      $this->arBanditQueue = $banditqueue;

      //patrolling police officers
      $selectedcops = array();
      $allcops = array();
      $allcops = $bod->_value['data'][0]['data']['featureData']['copsNBandits']['workers']['cops']['members'];
      if(isset($allcops) && count($allcops) > 0)
         foreach($allcops as $skey=>$sval)
         {
            if($sval['data']['state'] == 'state_patrolling')
               $selectedcops[] = (int)$skey;
            $this->arPoliceOfficer = $selectedcops;
         }
      //*****************************************************************************
	  $this->BanditCapturedDT = $bod->_value['data'][0]['data']['featureData']['downtownpolice']['numBanditsCaptured'];
      //DT bandit queue
      $banditqueueDT = array();
      $banditqueueDT = $bod->_value['data'][0]['data']['featureData']['downtownpolice']['banditQueue'];
      $this->arBanditQueueDT = $banditqueueDT;

      //DT patrolling police officers
      $selectedcops = array();
      $allcops = array();
      $allcops = $bod->_value['data'][0]['data']['featureData']['downtownpolice']['workers']['cops']['members'];
      if(isset($allcops) && count($allcops) > 0)
         foreach($allcops as $skey=>$sval)
         {
            if($sval['data']['state'] == 'state_patrolling')
               $selectedcops[] = (int)$skey;
            $this->arPoliceOfficerDT = $selectedcops;
         }
      //************************edit by Tonycell***************************
      $this->dogCaptured = $bod->_value['data'][0]['data']['featureData']['animalRescue']['numBanditsCaptured'];//addded by Tonycell
      //dog queue
      $banditqueue = array();
      $banditqueue = $bod->_value['data'][0]['data']['featureData']['animalRescue']['banditQueue'];
      $this->dogQueue = $banditqueue;

      //patrolling police officers
      $selectedcops = array();
      $allcops = array();
      $allcops = $bod->_value['data'][0]['data']['featureData']['animalRescue']['workers']['cops']['members'];
      if(isset($allcops) && count($allcops) > 0)
         foreach($allcops as $skey=>$sval)
         {
            if($sval['data']['state'] == 'state_patrolling')
               $selectedcops[] = (int)$skey;
            $this->dogOfficers = $selectedcops;
         }
      //*****************************************************************************
	  
      //************ Albertos ***********
      $this->arCars = array();
	  $carsNode = $bod->_value['data'][0]['data']['featureData']['cars'];
      if ((bool)$carsNode['carsenabled']==true)
      {
      	//we have cars enabled
      	foreach($carsNode['inventory'] as $kCar => $vCar)
      	{
      		$this->arCars[] = array("name"=>$kCar, "num"=>$vCar);
      	}
      }
      
      $this->arQuests = array();
      $questsNode = $bod->_value['data'][0]['metadata']['QuestComponent'];
      foreach((array) $questsNode as $qNode)
      {
      	$this->arQuests[] = $qNode;
      }

      $this->level = $bod->_value['data'][0]['data']['userInfo']['player']['level'];
      $this->gold = $bod->_value['data'][0]['data']['userInfo']['player']['gold'];
      $this->cash = $bod->_value['data'][0]['data']['userInfo']['player']['cash'];
      $this->xp = $bod->_value['data'][0]['data']['userInfo']['player']['xp'];
      $this->energy = $bod->_value['data'][0]['data']['userInfo']['player']['energy'];
      $this->energyMax = $bod->_value['data'][0]['data']['userInfo']['player']['energyMax'];
      //$this->fobjects = $bod->_value['data'][0]['data']['userInfo']['world']['objects'];
      $this->neighbors = $bod->_value['data'][0]['data']['userInfo']['player']['neighbors'];
      //added for franchises
      $this->franchises = $bod->_value['data'][0]['data']['franchises'];
      //added for inventory.wishlist
      $this->Inventory = (array)$bod->_value['data'][0]['data']['userInfo']['player']['inventory'];
      //added for collection overview
      $this->Collection = (array)$bod->_value['data'][0]['data']['userInfo']['player']['collections'];
      $this->wishlist = (array)$bod->_value['data'][0]['data']['userInfo']['player']['wishlist'];

      $this->Goods = $bod->_value['data'][0]['data']['userInfo']['player']['commodities']['storage']['goods'];
      if( ! isset($this->Goods))
         $this->Goods = 0;
	  $this->MaxGoods = $bod->_value['data'][0]['data']['userInfo']['world_summary']['world_main']['commoditySummary']['commodity']['goods']['capacity'] + 300;
      if( ! isset($this->MaxGoods))
         $this->MaxGoods = 0; 
		 
      $this->PremiumGoods = $bod->_value['data'][0]['data']['userInfo']['player']['commodities']['storage']['premium_goods'];
      if( ! isset($this->PremiumGoods))
         $this->PremiumGoods = 0;
		 
	  $PremiumGoodsMax1 = $bod->_value['data'][0]['data']['userInfo']['world_summary']['world_main']['commoditySummary']['commodity']['premium_goods']['capacity'];
  
	  $PremiumGoodsMax2 = $bod->_value['data'][0]['data']['userInfo']['world_summary']['world_downtown']['commoditySummary']['commodity']['premium_goods']['capacity'];
  


      $this->train = $bod->_value['data'][0]['data']['featureData']['trains']['workers'];// added by pjhkaka

      //added by Tonycell
      $this->EternalFountain = false;//default value
      // Redesigned by Tonycell
      $this->policelvl7 = false;//detects the police lvl7
     //$totalStorageGoods = 300;
//      $this->fobjects = array();
//      $this->fobjects1 = $bod->_value['data'][0]['data']['userInfo']['world']['objects'];
//      $this->fobjects2 = $bod->_value['data'][0]['data']['world']['objects'];
//      if(count($this->fobjects1) > 4)
//         $this->fobjects = $this->fobjects1;
//      if(count($this->fobjects2) > 4)
//         $this->fobjects = $this->fobjects2;

		 if ($this->currentWorld == "world_main")
		 {
			$this->fobjects = $this->LoadWorldObjects("world_main");
		 }
		 elseif ($this->currentWorld == "world_downtown")
		 {
			$this->dt_fobjects = $this->LoadWorldObjects("world_downtown");
		 }
		 else
		 {
			$this->dt_fobjects = $this->LoadWorldObjects("world_downtown");
			$this->fobjects = $this->LoadWorldObjects("world_main"); // load last so on first run bot will be in Main World.
		 }
      if(is_array($this->fobjects))
      {
         //$storages = $this->ld->Storages();//get the storages from XML
         foreach($this->fobjects as $fobj)
         {
            //if(isset($fobj['itemName']))
            //{
               //if(in_array($fobj['itemName'], $storages))
                     //{
                  //$totalStorageGoods += intval($storages[$fobj['itemName']]);
                     //}
	                                       //else
                                           //enjoy the loop and also finds for a lvl7 police station
                                           if($fobj['itemName'] == "mun_policestation_7")
                                           {
                                           $this->policelvl7 = true;
                                           }
                                            else
                                           if($fobj['itemName'] == "deco_golden_plow")
                                           {
                                           $this->EternalFountain = true;
                                           }
                   //if ($fobj['className'] == "StorageFacility")
						//{				   
		              //foreach ((array)$fobj['mechanicData']['slots'] as $k=>$house)
			                //{   
                         //if(isset($house['itemName']))
                                //{
                            //if(in_array($house['itemName'],$storages))
					                //{  
                                 //$totalStorageGoods += intval($storages[$house['itemName']]);
                                     //}       
                                //}
                            //}
						//}	
				
            //}
            }
        }

      //$this->MaxGoods = $totalStorageGoods;
	  $this->PremiumGoodsMax = $PremiumGoodsMax1 + $PremiumGoodsMax2 + 2000; 

      //added for daily bonus. 27-12-2010
      $this->currentBonusDay = $bod->_value['data'][0]['data']['userInfo']['player']['currentBonusDay'];
      $this->previousBonusDay = $bod->_value['data'][0]['data']['userInfo']['player']['previousBonusDay'];
      $this->previousBonusTime = $bod->_value['data'][0]['data']['userInfo']['player']['previousBonusTime'];
      //added to accept Neighbors work.
      $this->order_visitor_help = $bod->_value['data'][0]['data']['userInfo']['player']['Orders']['order_visitor_help']['received']['pending'];
      // show some up2date information.

      //Added by Tonycell
      $msg = $this->irc('ff') . '14,4';
      $msg .= $this->irc('cc') . '11,7 Coins: ' . $this->gold . ' ';
      $msg .= $this->irc('cc') . '0,12 Goods: ' . $this->Goods . '/' . $this->MaxGoods . ' ';
	  $msg .= $this->irc('cc') . '0,13 PremGoods: ' . $this->PremiumGoods . '/' . $this->PremiumGoodsMax . ' ';
      $msg .= $this->irc('cc') . '7,8 Energy: ' . $this->energy . ' ';
      $this->SendMsg($msg);
      //$this->SendMsg("> [Coins: $this->gold][Goods: $this->waresMax/$this->MaxGoods][Premium Goods: $this->PremiumMax][Energy: $this->energy]");
   }
   // ==============================================================================
   // ------------------------------------------------------------------------------
   // ==============================================================================
   function UserInfo()
   {

      $this->SendMsg('');
      //$tmp = explode(':', $this->userId);
      $this->SendMsg('# Zynga id = ' . $this->zySnuid);
      $this->SendMsg('# Name = ' . $this->usern);
      $this->SendMsg('# World Name = ' . $this->CityName);//addded by phreaker 26-02-2011
      $this->SendMsg('# Level = ' . $this->level);
      //$this->SendMsg('wood=' . $this->wood);
      $this->SendMsg('# XP = ' . $this->xp);
      $this->SendMsg('# Social Level = ' . $this->SocialLevel);//addded by phreaker 26-02-2011
      $this->SendMsg('# Cash = ' . $this->cash);
      $this->SendMsg('# Coins = ' . $this->gold);
      $this->SendMsg('# Energy = ' . $this->energy);
      $this->SendMsg('# EnergyMax = ' . $this->energyMax);
      $this->SendMsg('# Goods = ' . $this->Goods);
      $this->SendMsg('# GoodsMax = ' . $this->MaxGoods);
	  $this->SendMsg('# PremiumGoods = ' . $this->PremiumGoods);
      $this->SendMsg('# PremiumGoodsMax = ' . $this->PremiumGoodsMax);
      $this->SendMsg('# flashRevision = ' . $this->flashRevision);
      $this->SendMsg('# Host = ' . $this->host);
      $this->SendMsg('# x_flash_version = ' . $this->x_flash_version);

      //********************edit by sowijo_kaskuser**********************
      $this->SendMsg('# ======================================= ');
      //$this->SendMsg('# Bandit Spawn = ' . $this->Bandit);//addded by phreaker 15-03-2011
      $this->SendMsg('# Bandit Captured = ' . $this->BanditCaptured);//addded by phreaker 15-03-2011
      $allbandits = array();
      $allbandits = $this->arBanditQueue;
      if( ! empty($allbandits))
      {
         $smsg = '';
         foreach($allbandits as $skey=>$sval)$smsg .= '[bandit' . $sval . '] ';
         $this->SendMsg('# Bandit Queue: ' . $smsg);
      }
      else
      {
         $this->SendMsg('# Bandit Queue: None');
      }

      $allpolices = array();
      $allpolices = $this->arPoliceOfficer;
      if( ! empty($allpolices))
      {
         $smsg = '';
         foreach($allpolices as $sval)$smsg .= 'cop(' . $sval . ') ';
         $this->SendMsg('# Patrolling Police: ' . $smsg);
      }
      else
      {
         $this->SendMsg('# Patrolling Police: None');
      }
	  //********************************************************************
	  $this->SendMsg('# ======================================= ');
      $this->SendMsg('# Bandit CapturedDT = ' . $this->BanditCapturedDT);
      $allbandits = array();
      $allbandits = $this->arBanditQueueDT;
      if( ! empty($allbandits))
      {
         $smsg = '';
         foreach($allbandits as $skey=>$sval)$smsg .= '[bandit' . $sval . '] ';
         $this->SendMsg('# Bandit QueueDT: ' . $smsg);
      }
      else
      {
         $this->SendMsg('# Bandit QueueDT: None');
      }

      $allpolices = array();
      $allpolices = $this->arPoliceOfficerDT;
      if( ! empty($allpolices))
      {
         $smsg = '';
         foreach($allpolices as $sval)$smsg .= 'cop(' . $sval . ') ';
         $this->SendMsg('# Patrolling PoliceDT: ' . $smsg);
      }
      else
      {
         $this->SendMsg('# Patrolling PoliceDT: None');
      }
      //******************************************************************
      $this->SendMsg('# ======================================= ');
      //********************edit by Tonycell**********************
      //$this->SendMsg('# Doggie Spawn = ' . $this->Bandit);//addded by phreaker 15-03-2011
      $this->SendMsg('# Doggie Captured = ' . $this->dogCaptured);//addded by phreaker 15-03-2011
      $allbandits = array();
      $allbandits = $this->dogQueue;
      if( ! empty($allbandits))
      {
         $smsg = '';
         foreach($allbandits as $skey=>$sval)$smsg .= '[dog' . $sval . '] ';
         $this->SendMsg('# Doggie Queue: ' . $smsg);
      }
      else
      {
         $this->SendMsg('# Doggie Queue: None');
      }

      $allpolices = array();
      $allpolices = $this->dogOfficers;
      if( ! empty($allpolices))
      {
         $smsg = '';
         foreach($allpolices as $sval)$smsg .= 'lover(' . $sval . ') ';
         $this->SendMsg('# Doggie Lovers: ' . $smsg);
      }
      else
      {
         $this->SendMsg('# Doggie Lovers: None');
      }
      //******************************************************************

      //*** albertos Cars ****
      $this->SendMsg('# ======================================= ');
      if (!empty($this->arCars))
      {
      	$msg = "# Cars: ";
      	foreach($this->arCars as $arC)
      		$msg .= $arC["num"]. "x[".$arC["name"]."] ";
      		
      	$this->SendMsg($msg);
      } else {
      	 $this->SendMsg('# Cars: None or Not Enabled');
      }

      $this->SendMsg('# ======================================= ');
      $this->SendMsg('');
   }
   // ==============================================================================
   // ------------------------------------------------------------------------------
   // ==============================================================================
   function SendErrorMsg($msg)
   {
      echo $this->irc('b') . $this->irc('cc') . '4' . $msg . "\n";
   }
   function SendMsg($msg)
   {
      echo $msg . "\n";
   }

   // ==============================================================================
   function DownloadFile($url, $file_name)
   {
      $this->SendMsg('# Downloading ' . $file_name);

      if($this->GetParamByName("iProxyUse") == 1)
      {
         GetFile($this, $url, "tmp_dir\\" . $file_name, 1, $this->GetParamByName("sProxyHost"), $this->GetParamByName("iProxyPort"), $this->GetParamByName("sProxyUser"), $this->GetParamByName("sProxyPass"));
   }
      else
   {
         GetFile($this, $url, "tmp_dir\\" . $file_name, 0, '', '', '', '');
   }
   }

   // ==============================================================================
   function GetTrueXmlUrl($file_name)
   {
      //$url_from = "http://assets.cityville.zynga.com/" . $this->flashRevision ."/".  $file_name;
      $url_from = "http://cityvillefb.static.zgncdn.com/" . $this->flashRevision . "/" . $file_name;
      return $url_from;
   }

   // ==============================================================================
   //**********************edit ******************************
   function xmlz_decompress($fd)
   {
      $fname = "tmp_dir\\" . $fd;
      $fr = fopen($fname, 'r');
      $fl = fread($fr, filesize($fname));
      fclose($fr);

      $fn = substr($fname, 0, -2);

      $fw = fopen($fn, 'w');
      fwrite($fw, gzuncompress($fl));
      fclose($fw);
      echo '> Decompressing done.' . "\n";
   }
   //****************************************************
   function UpdateXML()
   {
      $this->SendMsg('UpdateXML');
      if(strcmp($this->flashRevision, $this->GetCurrentRevision()) != 0)
   {
         //$this->DownloadFile($this->GetTrueXmlUrl('Creatives.xml.z'), 'Creatives.xml.z');
         //$this->xmlz_decompress('Creatives.xml.z');
         //$this->DownloadFile($this->GetTrueXmlUrl('questSettings.xml'), 'questSettings.xml');
         //$this->DownloadFile($this->GetTrueXmlUrl('en.xml'), 'en.xml');

         //$this->DownloadFile($this->GetTrueXmlUrl('gameSettings.xml'), 'gameSettings.xml');
         //$this->DownloadFile($this->GetTrueXmlUrl('gameSettings.xml'), $this->flashRevision.'-gameSettings.xml');  //history versions
         $this->DownloadFile($this->GetTrueXmlUrl('gameSettings.xml.z'), 'gameSettings.xml.z');
         $this->xmlz_decompress('gameSettings.xml.z');
         copy("tmp_dir\\" . 'gameSettings.xml', "tmp_dir\\" . $this->flashRevision . '-gameSettings.xml');//history version

         //$this->DownloadFile($this->GetTrueXmlUrl('en_US.xml'), 'en_US.xml');
         $this->DownloadFile($this->GetTrueXmlUrl('en_US.xml.z'), 'en_US.xml.z');
         $this->xmlz_decompress('en_US.xml.z');

         //		 	$this->DownloadFile($this->GetTrueXmlUrl('it_IT.xml'), 'it_IT.xml');
         //			$this->DownloadFile($this->GetTrueXmlUrl('de_DE.xml'), 'de_DE.xml');
         //			$this->DownloadFile($this->GetTrueXmlUrl('fr_FR.xml'), 'fr_FR.xml');
         //			$this->DownloadFile($this->GetTrueXmlUrl('es_ES.xml'), 'es_ES.xml');
         //			$this->DownloadFile($this->GetTrueXmlUrl('id_ID.xml'), 'id_ID.xml');
         $this->DownloadFile($this->GetTrueXmlUrl('effectsConfig.xml'), 'effectsConfig.xml');

         if(file_exists('tmp_dir\fnames.txt'))
         {
            unlink('tmp_dir\fnames.txt');
   }
         $this->SetCurrentRevision($this->flashRevision);
      }
      if( ! file_exists('tmp_dir\gameSettings.xml'))
   {
         $this->SendMsg('Cannot find file gameSettings.xml');
         $this->SendMsg('Exit');
         exit;
      }
      $this->xmlsOb = new xmlsOb();
      $this->xmlsOb->GenerateFnames();

      //Added by Tonycell
      $this->banditlist = $this->GetBanditsFromXML(1);
      $this->dogList = $this->GetBanditsFromXML(2);
      $this->banditlistDT = $this->GetBanditsFromXML(3);

      // get cops and bandits data,
      $this->copsAndBandits = array(
                                    'bandits'=>array(),
                                                     'stations'=>array()//reserved
                                                                       );
      if(isset($this->xmlsOb->gsXML->copsandbandits->bandit))
         foreach($this->xmlsOb->gsXML->copsandbandits->bandit as $bandit)
         {
            $this->copsAndBandits['bandits'][] = $bandit;
         }

   }
   // ==============================================================================
      function DoWork()
   {
      $this->SendMsg('DoWork');
      $this->Hook('before_work');

      $this->ReloadConfig();
      $this->SendMsg('# Begin saving user inventory to local db file');
      $this->ld->SaveInventory2db($this);
      if($this->firstrun)
      {
         $this->SendMsg('# Creating plugin-settings on local db file');
         $this->ld->CreatePluginSettings($this);//added by Tonycell - to avoid the 1st run saving data problem
      }
      $this->Hook('get_inbox_requests');

      $this->Hook('neighbor_list');//NeighborList
      $this->Hook('pending_franchises');//Plugin Neighbors (Pending Franchise requests)


	  $this->Hook('KPD');
      $this->Hook('start_inbox');//Plugin Inbox by Tonycell
      $this->Hook('InstandReady');	  
	  $this->Hook('start_neighbors');//Plugin Neighbors by Tonycell
      $this->Hook('start_crops');//Plugin Crops by Tonycell
	  $this->Hook('start_im-export');
      $this->Hook('start_buildings');//Plugin Buildings by Tonycell
	  

      //$this->Hook('before_harvest_crops'); //no plugin assigned
      //$this->Hook('after_harvest_crops'); //no plugin assigned
	  
      //$this->Hook('before_seed_crops'); //no plugin assigned
      //$this->Hook('after_seed_crops'); //no plugin assigned

      //$this->Hook('before_buildings_work'); //no plugin assigned
      //$this->Hook('after_buildings_work'); //no plugin assigned
	  
      //$this->Hook('accept_pending_franchises');
	  
      $this->Hook('fill_goods_before');//Plugin Multi
      $this->Hook('before_help_neighbors');//no plugin assigned
      $this->Hook('help_neighbors');//no plugin assigned
      $this->Hook('after_help_neighbors');//no plugin assigned


      $this->Hook('before_other_work');//Plugin CityReq & Neighbors & Wall
      $this->Hook('other_work');//Plugin CityReq, Coin3, Coin4, Factory, Map, Multi, Neighbors, Sell, UnlimitedLink
      $this->Hook('after_other_work');//no plugin assigned
      $this->Hook('fill_goods_after');//Plugin Multi

      //Please do not spent any energy in this hook
      $this->Hook('after_work');//GameInfo plugin
	  
	  $this->currentWorld = ""; // remove current world so both worlds are reloaded when ReloadConfig() is executed
      $this->ReloadConfig();
      $this->SendMsg('# Begin saving user profile to local db file');
      $this->ld->SaveProfile2db($this);
      $this->SendMsg('# End saving user profile to local db file');
      $this->Hook('download_images');
   }
   // ==============================================================================
   function GetParamByName($name)
   {
      $fl = file('options.ini');
      foreach($fl as $line)
      {
         if(strpos($line, $name) !== false)
         {
            $pos = strpos($line, '=');
            $val = trim(substr($line, $pos + 1, strlen($line)));
         }
      }
      return $val;
   }

   // ==============================================================================
   /*
   function SendRequest_($data, $doober)
   {
   		$response = $this->Request($data);
   $this->CheckDoober = $doober;
   		$this->CheckServerError($response);
   		return $response;
   	}
   	function SendRequest($data) { return $this->SendRequest_($data, true); }
   	function SendRequestNODOOBER($data) { return $this->SendRequest_($data, false); }
   */
   function SendRequest($data)
   {
      $response = $this->Request($data);
      //$this->CheckServerError($response);
      return $response;
   }
   // ------------------------------------------------------------------------------
   function Disconnect()
   {
      fclose($this->s);
   }

   // ------------------------------------------------------------------------------
   function Connect()
   {
      //before -
      /*
      		if ($this->GetParamByName("iProxyUse") == 1) {
      			$this->s = fsockopen($this->GetParamByName("sProxyHost"), $this->GetParamByName("iProxyPort"));
      		}
      		else{
      			//$this->SendMsg("headers:". $this->headers["Host"]);
      			$this->s = fsockopen($this->headers["Host"], 80, $errNo, $errStr, 30);
      		}*/
      //after - [] proxy function temporary disabled
      try
      {
         $this->s = fsockopen($this->headers["Host"], 80, $errNo, $errStr, 30);
         //$this->s = fsockopen("50.16.254.26", 80, $errNo, $errStr, 30);
      }
      catch(Exception$e)
      {
         echo '*** Caught exception: ', $e->getMessage(), "\n";
      }

      $ctry = 0;
      if($errNo > 0)
      {
         $this->SendMsg('=====================================');
         while( ! $this->s && ($ctry < 3))
         {
            $this->SendErrorMsg('ERROR: (' . $errNo . ') ' . $errStr);
            $ctry++;
            $this->SendMsg('Connection try #' . $ctry . ' ...');

            //before -
            /*if ($this->GetParamByName("iProxyUse") == 1)
            {
            			    $this->s = fsockopen($this->GetParamByName("sProxyHost"), $this->GetParamByName("iProxyPort"));
            		    }
            		    else
            {
            			  $this->s = fsockopen($this->headers["Host"], 80, $errNo, $errStr, 30);
            		    }*/
            //after - proxy function temporary disabled
            $this->s = fsockopen($this->headers["Host"], 80, $errNo, $errStr, 30);
            //$this->s = fsockopen("50.16.254.26", 80, $errNo, $errStr, 30);

         }
         if($this->s)
         {
            $this->SendMsg('Connection estabilished again. Continuing work in progress...');
            $this->SendMsg('=====================================');
         }
      }

      if( ! $this->s)
      {
         $this->SendMsg("Error: Can't connect to game server");
         exit;
      }
   }

   // ------------------------------------------------------------------------------
   function fullread($sd, $len)
   {
      $ret = '';
      $read = 0;

      while($read < $len && ($buf = fread($sd, $len - $read)))
      {
         $read += strlen($buf);
         $ret .= $buf;
      }

      return $ret;
   }

   // ------------------------------------------------------------------------------
   function Request($data)
   {
      $this->Connect();
      if(strpos($this->url, 'http://') === false)
         $query = "POST http://" . $this->host . $this->url . " HTTP/1.1\r\n";
      else
         $query = "POST $this->url HTTP/1.1\r\n";

      //$query = "POST http://" . $this->host . $this->url . " HTTP/1.1\r\n";

      if($this->GetParamByName("iProxyUse") == 1)
      {
         $authorization = base64_encode(trim($this->GetParamByName("sProxyUser")) . ':' . trim($this->GetParamByName("sProxyPass")));
         $this->headers["Proxy-Authorization"] = "Basic $authorization";
      }
	  
      foreach($this->headers as $key=>$value)
      {
         $query .= $key . ": " . $value . "\r\n";
      }

      $query .= "Content-Length: " . strlen($data) . "\r\n\r\n";
      $query .= $data;

      stream_set_blocking($this->s, 1);
      fwrite($this->s, $query);
      stream_set_timeout($this->s, 10);

      $answer = '';

      $max_tick = 500;// wait max 50 seconds for data before we repeat request
      $cur_tick = 0;
      $is_bad = false;

      while( ! strlen($answer))
      {
         $answer .= $this->fullread($this->s, 1024);

         if( ! strlen($answer))
         {
            usleep(1000000);
            $cur_tick++;

            if($cur_tick > $max_tick)
   {
               $is_bad = true;
               break;
            }
         }
      }

      if($is_bad)
      {
         $this->SendMsg("Repeat request -no answer-");
         $this->Disconnect();
         $this->Connect();
         return $this->SendRequest($data);
      }

      if(strpos($answer, '404 Not Found') !== false)
      {
         $this->Disconnect();
         $this->Connect();
         $this->SendMsg("Repeat request -404-");
         return $this->SendRequest($data);
      }


      if(strripos($answer, '500 Internal Server Error') !== false)
      {
        $this->SendMsg("ERROR: Internal Server Error");
        $this->Disconnect();

        global $headers_file, $amfbin_file;

            if(file_exists($headers_file))
              unlink($headers_file);//remove the reader if exists
            if(file_exists($amfbin_file))
              unlink($amfbin_file);//remove AMF data if exists
            if(file_exists('tmp_dir\CurrentRevision.txt'))
              unlink('tmp_dir\CurrentRevision.txt');

          $this->RestartBot();
          return;
   }

      if(strripos($answer, '502 Bad Gateway') !== false)
      {
         $this->SendMsg("ERROR: 502 Bad Gateway");
         return 0;
      }

      preg_match('/Content-length:[\s]([0-9]*)[\s]/si', $answer, $match);
      $pos = strpos($answer, "\r\n\r\n");
      if($pos !== false)
      {
         $answer = substr($answer, $pos + 4, strlen($answer));
      }
      else
         $answer = null;

      while(true)
      {
         if( ! isset($Loaded_Size) || ($Loaded_Size == 0))
            $Loaded_Size = @$match[1];
         if($Loaded_Size == 0)
         {
            echo 'Debug: Read ' . strlen($answer) . ' wanted: ' . @$match[1] . ' Answer: ' . $answer . "\n";
            $this->SendMsg("ERROR: Lost connection to server");
            $this->SendRequest($data);
         }
         $answer .= $this->fullread($this->s, $Loaded_Size);

         if(strlen($answer) >= $match[1])
            break;
         usleep(100000);
   }

      if(isset($Loaded_Size) && ($Loaded_Size == $match[1]))
         $Loaded_Size = 0;
      return $answer;

      $this->Disconnect();
   }

   function Deserialize($response)
   {
      $tmp = new AMFObject($response);
      $deserializer = new AMFDeserializer($tmp->rawData);
      $deserializer->deserialize($tmp);
      return $tmp;
   }

   // ==============================================================================
   function CheckServerError($tmp)
   {

      //$tmp = new AMFObject($resp);
      //$deserializer = new AMFDeserializer($tmp->rawData);
      //$deserializer->deserialize($tmp);
	  
      if(isset($tmp->_bodys[0]->_value['data'][0]['data']['result']))
      {
         // added by 12Christiaan	 result  String  failure
         if($tmp->_bodys[0]->_value['data'][0]['data']['result'] == "failure")           {$this->error_msg = "Unknown error";}
         if($tmp->_bodys[0]->_value['data'][0]['data']['result'] == "batchFailure")           {$this->error_msg = "Unknown batchFailure error";}
      }
      //added 2010-12-19 by 12christiaan found by Altizar
      if(isset($tmp->_bodys[0]->_value['faultCode']))
         $this->error_msg = $tmp->_bodys[0]->_value["faultCode"];
      //if (isset($tmp->_bodys[0]->_value['data'][0]['errorData'])) $this->error_msg = $tmp->_bodys[0]->_value['data'][0]['errorData'];
      //if (isset($tmp->_bodys[0]->_value['errorData'])) $this->error_msg = $tmp->_bodys[0]->_value['errorData'];


      //connection errors
      $NO_ERROR = 0;
      $ERROR_AUTH = 1;
      $OUTDATED_GAME_VERSION = 10;
      $AUTH_NO_USER_ID = 26;
      $AUTH_NO_SESSION = 27;
      //reponse
      $RETRY_TRANSACTION = 28;//Sequence OOS
      $FORCE_RELOAD = 29;

      $eint = 0;
      if(isset($tmp->_bodys[0]->_value['errorType']))
         $eint = $tmp->_bodys[0]->_value['errorType'];
      if($eint > 0)
      {
         if(in_array($eint, array($ERROR_AUTH, $OUTDATED_GAME_VERSION, $AUTH_NO_USER_ID, $AUTH_NO_SESSION, $FORCE_RELOAD)))
         {
            $this->SendErrorMsg('ERROR: (' . $eint . ') ' . $tmp->_bodys[0]->_value['errorData']);
            $this->SendErrorMsg('Restarting the Bot in 5 seconds');
            sleep(5);
            global $headers_file, $amfbin_file;

            if(file_exists($headers_file))
               unlink($headers_file);//remove the reader if exists
            if(file_exists($amfbin_file))
               unlink($amfbin_file);//remove AMF data if exists
            if(file_exists('tmp_dir\CurrentRevision.txt'))
               unlink('tmp_dir\CurrentRevision.txt');
            $this->RestartBot();
         }
      }

      $eint = 0;
      if(isset($tmp->_bodys[0]->_value['data'][0]['errorType']))
         $eint = $tmp->_bodys[0]->_value['data'][0]['errorType'];
      if($eint > 0)
         $this->error_msg = '[' . $eint . '] ' . $tmp->_bodys[0]->_value['data'][0]['errorData'];

      /*		if (isset($this->error_msg))
      {
      			$this->SendErrorMsg('ERROR: ' . $this->error_msg);
      			// changed if by 12christiaan to detect AMFPHP_RUNTIME_ERROR  found by Altizar
      			if (($this->error_msg == 'AMFPHP_RUNTIME_ERROR') ||
      ($this->error_msg == 'User not found') ||
      (strpos($this->error_msg, "There is a new version of the game released")!==false))
      {
      				$this->SendErrorMsg('The session expired, the bot will restart in 5 seconds');
      				sleep(5);
      				global $headers_file, $amfbin_file;

      				if (file_exists($headers_file)) unlink($headers_file); //remove the reader if exists
      				if (file_exists($amfbin_file)) unlink($amfbin_file); //remove AMF data if exists
      				if (file_exists('tmp_dir\CurrentRevision.txt')) unlink('tmp_dir\CurrentRevision.txt');
      				$this->RestartBot();
      return;
   }
      		}
      */
      // added by 12Christiaan to prevent  AMFPHP_RUNTIME_ERROR
      if(isset($tmp->_bodys[0]->_value['zySig']['zySig']))
   {
         if($this->zySig != $tmp->_bodys[0]->_value['zySig']['zySig'])
         {
            //$this->SendMsg("zySig updated **************************************");
            $this->zySig2 = $tmp->_bodys[0]->_value['zySig']['zySig'];

            $file = 'tmp_dir\\' . $this->zySnuid . '_amf.bin';

            $fl = fopen($file, 'r');
            @$content = fread($fl, filesize($file));
            fclose($fl);

            $content = str_replace($this->zySig, $this->zySig2, $content);

            $fl = fopen($file, 'w');
            fwrite($fl, $content);
            fclose($fl);

            $this->zySig = $this->zySig2;
         }
      }
   }
   // =========================================================================== by Tonycell
   function CheckResponse($request)
   {
      //response error
      $ERROR_USER_DATA_MISSING = 2;
      $ERROR_INVALID_STATE = 3;
      $INVALID_DATA = 4;
      $MISSING_DATA = 5;
      $ACTION_CLASS_ERROR = 6;
      $ACTION_METHOD_ERROR = 7;
      $ERROR_RESOURCE_DATA_MISSING = 8;
      $NOT_ENOUGH_MONEY = 9;
      $TRANSPORT_FAILURE_GENERAL = 25;

      //$amf = new AMFObject($request);
      //$deserializer = new AMFDeserializer($amf->rawData);
      //$deserializer->deserialize($amf);
      //$bod = new MessageBody();
      $bod = $request->_bodys[0];

      $msg = "";
      if(isset($bod->_value['data'][0]['data']) && (is_int($bod->_value['data'][0]['data'])))
      {
         switch($bod->_value['data'][0]['data'])
         {
            case $ERROR_USER_DATA_MISSING: $msg = "ERROR_USER_DATA_MISSING";break;
            case $ERROR_INVALID_STATE: $msg = "ERROR_INVALID_STATE";break;
            case $INVALID_DATA: $msg = "INVALID_DATA";break;
            case $MISSING_DATA: $msg = "MISSING_DATA";break;
            case $ACTION_CLASS_ERROR: $msg = "ACTION_CLASS_ERROR";break;
            case $ACTION_METHOD_ERROR: $msg = "$ACTION_METHOD_ERROR";break;
            case $ERROR_RESOURCE_DATA_MISSING: $msg = "ERROR_RESOURCE_DATA_MISSING";break;
            case $NOT_ENOUGH_MONEY: $msg = "NOT_ENOUGH_MONEY";break;
            case $TRANSPORT_FAILURE_GENERAL: $msg = "TRANSPORT_FAILURE_GENERAL";break;
            default: $msg = '[' . $bod->_value['data'][0]['data'] . '] Unknown error';
         }
      }
      else
         if(isset($bod->_value['data'][0]['errorType']) && ($bod->_value['data'][0]['errorType'] == 0))
            $msg = "success";
         else
            $msg = $this->irc('cc') . '4[' . $bod->_value['data'][0]['errorType'] . ']' . $bod->_value['data'][0]['errorData'];//response from the query ("success"

      return $msg;
   }
   //============================================================================ by Tonycell
   function CheckDoobers($tmp)
   {
      //$tmp = new AMFObject($resp);
      //$deserializer = new AMFDeserializer($tmp->rawData);
      //$deserializer->deserialize($tmp);

      $d = $tmp->_bodys[0]->_value['data'][0]['data']['doobers'];
      if( ! isset($d))
         $d = $tmp->_bodys[0]->_value['data'][0]['data']['data']['doobers'];
	  if( ! isset($d))
         $d = $tmp->_bodys[0]->_value['data'][0]['data']['rewardResult']['doobers'];//doobers on redeemVisitorHelpAction
      if( ! isset($d))
         $d = $tmp->_bodys[0]->_value['data'][1]['data']['data']['doobers'];//doobers on visiting neighbors
	  if( ! isset($d))
         $d = $tmp->_bodys[0]->_value['data'][1]['data']['doobers'];//doobers on CustomResidence

      if(isset($d) && is_array($d) && (count($d) > 0))
      {
         //We got a Reward.
         $msg = "";
         foreach($d as $doober)
         {
            $msg .= '(' . $doober[0] . ' x ' . $doober[1] . ')';
            if($doober[0] == "coin")              {$this->dooberItems++;$this->dooberItem[$doober[0]] += $doober[1];}
            if($doober[0] == "xp")              {$this->dooberItems++;$this->dooberItem[$doober[0]] += $doober[1];}
            if($doober[0] == "collectable")              {$this->dooberItems++;$this->dooberItem[$doober[1]] += 1;}
            if($doober[0] == "energy")              {$this->dooberItems++;$this->dooberItem[$doober[0]] += $doober[1];}
         }
         //if($msg!="") $this->SendMsg("# Doobers: $msg");
         $this->SendMsg($this->irc('cc') . '7DOOBERS: ' . $msg);
      }
      //$this->streakBonusCheck();
      //$this->streakBonus3();
   }

   // ==============================================================================
   function RestartBot()
   {
      SendApi('BotApi.RUNNOW');
      exit;
   }

   // ==============================================================================
   function GetSequense()
   {
      $this->sequense += 1;
      return $this->sequense;
   }

   // ==============================================================================
   function Add2Report($name)
   {
      if( ! isset($this->error_msg))
      {
         $this->statistics[$name][] = 1;
         $this->lastAction = $name;
      }
   }
   // ==============================================================================
   function GetCurrentRevision()
   {
      if(file_exists("tmp_dir\CurrentRevision.txt"))
      {
         $fl = fopen('tmp_dir\CurrentRevision.txt', 'r');
         $currver = fread($fl, filesize("tmp_dir\CurrentRevision.txt"));
         fclose($fl);
         return $currver;
      }
      else
      {
         return false;
      }
   }
   // ==============================================================================
   function SetCurrentRevision($ver)
   {
      if(file_exists("tmp_dir\CurrentRevision.txt"))
      {
         unlink("tmp_dir\CurrentRevision.txt");
      }

      $fl = fopen('tmp_dir\CurrentRevision.txt', 'w');
      fwrite($fl, $ver);
      fclose($fl);
   }
   // ==============================================================================
   // ========================= nice time. Facebook style.
   function nicetime($date)
   {
      if(empty($date))
      {
         return "No date provided";
      }

      $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
      $lengths = array("60", "60", "24", "7", "4.35", "12", "10");

      $now = time();
      //	$unix_date	   = strtotime($date);  // Do not provide real date, but unix timestamp
      $unix_date = $date;

      // check validity of date
      if(empty($unix_date))
      {
         return "Bad date";
      }
	  
      // is it future date or past date
      if($now > $unix_date)
      {
         $difference = $now - $unix_date;
         $tense = "ago";
	  
      }
	  else
      {
         $difference = $unix_date - $now;
         $tense = "from now";
   }

      for($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++)
   {
         $difference /= $lengths[$j];
      }

      $difference = round($difference);

      if($difference != 1)
      {
         $periods[$j] .= "s";
      }

      return "$difference [$j] {$tense}";
   }
   
   
   
   
   
   //////////////////////////////////////////// PLUG STAGE ////////////////////////////////////////////
   
 
   // ==========================================================================
   // Harvest Ships, Cruiser, Crops and Factory / Clear Crop=====================
   // ==========================================================================
   function harvestAction($obj, $operation, $flag)
   {

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "WorldService.performAction";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $operation;
      $amf->_bodys[0]->_value[1][0]['params'][1] = $obj;
      //$amf->_bodys[0]->_value[1][0]['params'][2] = null;
      //$amf->_bodys[0]->_value[1][0]['params'][2][0] = '';
      $amf->_bodys[0]->_value[1][0]['params'][2] = microtime(true);
	  
	  
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);
	  if($operation == "harvest") $this->SendMsg($this->irc('cc') . '2(' . $msg . ') Harvesting: ' . $obj['itemName'] . ' (id:' . $obj["id"] . ')' . ' [' . $obj['contractName'] . "]  x=" . $obj['position']['x'] . " y=" . $obj['position']['y']);
      else
      if($operation == "clear") $this->SendMsg($this->irc('cc') . '7(' . $msg . ') Clearing withered: [' . $obj['contractName'] . '] x=' . $obj['position']['x'] . ' y=' . $obj['position']['y'] . ' id:' . $obj["id"]);

      $this->CheckDoobers($x);//check for any doobers
      //$this->streakBonus3();  //moved to the plugin directly as an option

	  if($operation == "harvest") $text1 = 'Harvest '.$flag;
	  if($operation == "clear") $text1 = 'Clear '.$flag;
      $this->Add2Report($text1);
   }
   // ==============================================================================
   // startContract Crop, Ship, Cruiser and Factory=================================
   // ==============================================================================
   function startContract($obj, $itemName, $sname, $flag)
   {

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "WorldService.performAction";
      $amf->_bodys[0]->_value[1][0]['params'][0] = "startContract";
      $amf->_bodys[0]->_value[1][0]['params'][1] = $obj;
      $amf->_bodys[0]->_value[1][0]['params'][1]['state'] = 'planted';
      $amf->_bodys[0]->_value[1][0]['params'][1]['contractName'] = $sname;
	  //if($itemName == "plot_crop") 
      $amf->_bodys[0]->_value[1][0]['params'][1]['itemName'] = $itemName;
      $amf->_bodys[0]->_value[1][0]['params'][1]['plantTime'] = microtime(1) * 1000;;
      $amf->_bodys[0]->_value[1][0]['params'][2] = null;
      $amf->_bodys[0]->_value[1][0]['params'][2][0] = '';


      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);
	  
	  $msg = $this->CheckResponse($x);
	  if(($flag == "Main Factory") || ($flag == "Downtown Factory"))
	  $this->SendMsg($this->irc('cc') . '3(' . $msg . ') start ' . $sname . " in "  . $obj['itemName'] . " x=" . $obj['position']['x'] . " y=" . $obj['position']['y']);
	  if(($flag == "Ship") || ($flag == "Cruiser"))
	  $this->SendMsg($this->irc('cc') . '3(' . $msg . '): Send ' . $obj['itemName'] . ' (id:' . $obj["id"] . ') to ' . $sname . '');
	  if($flag == "Crop") 
	  $this->SendMsg($this->irc('cc') . '3(' . $msg . ') Planting crop (' . $sname . ") x=" . $obj['position']['x'] . " y=" . $obj['position']['y']);

	  
	  $text1 = 'start Contract '.$flag;
      $this->Add2Report($text1);
   }    
   // ==============================================================================
   // Use Consumable [Energy/Goods] ================================================
   // ==============================================================================
   //BuyEnergy
   //BuyGoods
   function useConsumable($functionName, $item)
   {
      if($functionName == "UserService.buyEnergy") $this->SendMsg("[Energy] Using Energy from inventory: $item");
	  if($functionName == "UserService.buyGoods") $this->SendMsg("[Goods] Using Goods from inventory: $item");
	  
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = $functionName;
      $amf->_bodys[0]->_value[1][0]['params'][0] = (string)$item;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $this->Add2Report($item.' used from inventory');
   }
   // ==============================================================================
   function addToWishlist($item)
   {
      $this->SendMsg("@ addToWishlist: $item");

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "CollectionsService.addToWishlist";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $item;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $this->Add2Report('addToWishlist');
	    } 
   // ==============================================================================
   function AcceptBonus()
   {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.collectDailyBonus";
      $amf->_bodys[0]->_value[1][0]['params'] = array();

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $this->Add2Report('DailyBonus');
   }
   // ==============================================================================
   // Objects [Residences, Zoos, Wildernes]
   // ==============================================================================
   function ObjectAction($obj, $operation, $flag)
   {
      //$this->SendMsg('[BUILDINGS-Residences] Collect rent from (' . $obj['itemName'] . ") x=" . $obj['position']['x'] . " y=" . $obj['position']['y']);

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;
	  
      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);

      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "WorldService.performAction";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $operation;
      $amf->_bodys[0]->_value[1][0]['params'][1] = $obj;
      $amf->_bodys[0]->_value[1][0]['params'][2] = microtime(true);
      $amf->_bodys[0]->_value[1][0]['params'][3] = Array();
      $amf->_bodys[0]->_value[1][0]['params'][3][0] = '';

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);
	  if($operation == "harvest") $this->SendMsg($this->irc('cc') . '2(' . $msg . ') Harvesting: [' . $obj['itemName'] . "] x=" . $obj['position']['x'] . " y=" . $obj['position']['y']);
      else
      if($operation == "clear") $this->SendMsg($this->irc('cc') . '5(' . $msg . ') Choping: ' . $obj['itemName'] . ' (id:' . $obj["id"] . ') [x=' . $obj["position"]["x"] . ' y=' . $obj["position"]["y"] . ']');
                     
					 
      //if (isset($this->error_msg)) $this->ReloadConfig();
      $this->CheckDoobers($x);
      //$this->streakBonus3();  //moved to the plugin directly as an option

	  if($operation == "harvest") $text1 = 'Harvest '.$flag;
	  if($operation == "clear") $text1 = 'Chop '.$flag;
      $this->Add2Report($text1);
   }
   // ===========================================================================
   // Municipal / Landmark
   // ===========================================================================
   function collectCommun($obj, $operation, $flag)
   {
      //$this->SendMsg('[Community] Harvesting (' . $obj['itemName'] . ") x=" . $obj['position']['x'] . " y=" . $obj['position']['y'] . " id:" .$obj["id"]);
      
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);

      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "WorldService.performAction";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $operation;
      $amf->_bodys[0]->_value[1][0]['params'][1] = $obj;
      $amf->_bodys[0]->_value[1][0]['params'][2] = microtime(true);
      //$amf->_bodys[0]->_value[1][0]['params'][2][0] = '';
      

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);
      //$this->SendMsg("Harvesting (" . $obj['itemName'] . ") x=" . $obj['position']['x'] . " y=" . $obj['position']['y'] . " id:" .$obj["id"]);
      $this->SendMsg($this->irc('cc') . '2(' . $msg . ') Harvesting: [' . $obj['itemName'] . '] x=' . $obj['position']['x'] . ' y=' . $obj['position']['y']);

      $this->CheckDoobers($x);//check for any doobers+streakBonus
      //$this->streakBonus3(); Moved to Plugin

	  if($operation == "harvest") $text1 = 'Harvest '.$flag;
	  if($operation == "supply") $text1 = 'Supply '.$flag;
	  if($operation == "process") $text1 = 'Send Commuters '.$flag;
   }
   // ==============================================================================
    /*function collectCustom($obj)
   {
      unset($this->error_msg);

      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
	  
	  
      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);

      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell
      //1st transaction
      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "GameMechanicService.performMechanicAction";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $obj["id"];
      $amf->_bodys[0]->_value[1][0]['params'][1] = "harvestEndTS";
      $amf->_bodys[0]->_value[1][0]['params'][2] = "GMPlay";
      $amf->_bodys[0]->_value[1][0]['params'][3]['operation'] = "harvest";
	  $amf->_bodys[0]->_value[1][0]['params'][3]['clientEnqueueTime'] = microtime(true);
	  //2nd transaction
	  $amf->_bodys[0]->_value[1][1]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][1]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][1]['enqueueTime'] = floatval($enqueueTime);//by Tonycell
      $amf->_bodys[0]->_value[1][1]['sequence'] = $this->GetSequense();;
	  $amf->_bodys[0]->_value[1][1]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][1]['functionName'] = "WorldService.performAction";
      $amf->_bodys[0]->_value[1][1]['params'][0] = "harvest";
      $amf->_bodys[0]->_value[1][1]['params'][1] = $obj;
      $amf->_bodys[0]->_value[1][1]['params'][2] = microtime(true);
      $amf->_bodys[0]->_value[1][1]['params'][3] = Array();
      $amf->_bodys[0]->_value[1][1]['params'][3][0] = '';


      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $bod = $x->_bodys[0];
	  

      //$msg = $this->CheckResponse($x);
      $msg = $bod->_value['data'][0]['data']['result'];

	  //$this->SendMsg($this->irc('cc') . '2(' . $msg . ') Harvesting: [' . $obj['itemName'] . '] x=' . $obj['position']['x'] . ' y=' . $obj['position']['y']);
	  $this->SendMsg($this->irc('cc') . '2(' . $msg . ')');
      //$this->SendMsg("($msg): $text" . $obj['itemName'] . ' (id:'.$obj["id"].')'); }
	  
	  $this->CheckDoobers($x);
	  //$$this->streakBonus3();
	  
      $this->Add2Report('CustomResidence');
   }  */ 
   // ==============================================================================
   // Business [collect, supply with "goods"/"premium_goods"]
   // ==============================================================================
   //function collectBB($obj, $silent = true)
   //function supplyBB($obj, $silent = true) "goods"
   //function supplyBBB($obj, $silent = true) "premium_goods"
   function actionBusiness($operation, $obj, $state, $param, $flag)
   {

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

	  $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);

      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "WorldService.performAction";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $operation;
      $amf->_bodys[0]->_value[1][0]['params'][1] = $obj;
      $amf->_bodys[0]->_value[1][0]['params'][1]['state'] = $state;
      $amf->_bodys[0]->_value[1][0]['params'][2] = microtime(true);	  
      $amf->_bodys[0]->_value[1][0]['params'][3] = Array();
      //$amf->_bodys[0]->_value[1][0]['params'][2][0] = $this->xmlsOb->GetBuildingsProductCount($obj['itemName']);
      $amf->_bodys[0]->_value[1][0]['params'][3][0] = $param; //(int)$obj['lastSavedMax'];total of goods/visit needed


      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);//sending request
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);
      if($operation == "harvest") $this->SendMsg($this->irc('cc') . '2(' . $msg . ') Harvesting: [' . $obj['itemName'] . '] x=' . $obj['position']['x'] . ' y=' . $obj['position']['y']);
      if($operation == "openBusiness") $this->SendMsg($this->irc('cc') . '3(' . $msg . ') Supplying: [' . $obj['itemName'] . '] x=' . $obj['position']['x'] . ' y=' . $obj['position']['y']);
	  
      $this->CheckDoobers($x);
      //$this->streakBonus3();
	  if($operation == "harvest") $text1 = 'Harvest '.$flag;
	  if($operation == "openBusiness") $text1 = 'Supply '.$flag;
	  if($operation == "process") $text1 = 'Send Commuters '.$flag;
      $this->Add2Report($text1);
   }
   // ============================================================================== by pjhkaka
   function NewObjectAction($obj, $param, $mode, $operation, $flag)
   {
      unset($this->error_msg);

      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);

      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "GameMechanicService.performMechanicAction";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $obj["id"];
      $amf->_bodys[0]->_value[1][0]['params'][1] = $param;
      $amf->_bodys[0]->_value[1][0]['params'][2] = $mode;
      $amf->_bodys[0]->_value[1][0]['params'][3]['operation'] = $operation; //flag
	  if($flag == "Powerstation")
	  { 
      $amf->_bodys[0]->_value[1][0]['params'][3]['operation'] = "streakData";
      $amf->_bodys[0]->_value[1][0]['params'][3]['action'] = $operation;
	  }

      //added by Tonycell
      $amf->_bodys[0]->_value[1][0]['params'][3]['clientEnqueueTime'] = microtime(true);

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);
      if($operation == "harvest") $this->SendMsg($this->irc('cc') . '2(' . $msg . ') Harvesting: ' . $obj['itemName'] . ' (id:' . $obj["id"] . ')');
      else
      if($operation == "supply") $this->SendMsg($this->irc('cc') . '3(' . $msg . ') Supplying: ' . $obj['itemName'] . ' (id:' . $obj["id"] . ')');
	  else
      if($operation == "process") $this->SendMsg($this->irc('cc') . '14(' . $msg . ') Visiting: ' . $obj['itemName'] . ' (id:' . $obj["id"] . ')');
    
	  if(($flag == "Bridge") || ($flag == "BusStop") || ($flag == "Skyscraper") || ($flag == "Ferry") || ($flag == "SubWay"))
	  $this->CheckDoobers($x);
	  //$$this->streakBonus3();
	  
	  
	  if($operation == "harvest") $text1 = 'Harvest '.$flag;
	  if($operation == "supply") $text1 = 'Supply '.$flag;
	  if($operation == "process") $text1 = 'Send Commuters '.$flag;
      $this->Add2Report($text1);

   }
   // ==============================================================================
      function processVisits($obj, $silent = true)
   {
      $extraVisits = $obj['lastSavedMax'] - $obj['visits'];
      if($obj["className"] == "Hotel" ||
      $obj["className"] == "Mall" ||
      $obj["className"] == "Mall2" ||
	  $obj["className"] == "Subway" ||
	  $obj["className"] == "ThemePark" ||
      $obj["className"] == "SocialBusiness" ||
      //(isset($obj["derivesFrom"]) && (in_array($obj["derivesFrom"],array("hotel_sailboat_low","casino_social_business")))) ||
      (isset($obj["derivesFrom"]) && (($obj["derivesFrom"] == "hotel_sailboat_low") || ($obj["derivesFrom"] == "casino_social_business")))
      )
      {
         $extraVisits = intval($obj['mechanicData']['harvestState']['customersReq']) - intval($obj['mechanicData']['harvestState']['customers']);
         //$this->SendMsg("$extraVisits times ");
   }

      unset($this->error_msg);


      $this->SendMsg($this->irc('cc') . '14Visiting: [' . $obj['itemName'] . "] $extraVisits times.");	  
	  
      for($i = $extraVisits; $i > 0; $i = $i - 100)
   {
         if($i > 100)
            $this->processVisitsFragment($obj, 100, $silent);
         else
            $this->processVisitsFragment($obj, $i, $silent);
      }
      $this->Add2Report('processVisits');
   }
   // ==============================================================================
   function processVisitsFragment($obj, $extraVisits, $silent = true)
   {
      // if($silent) $this->SendMsg("$extraVisits times ");
      unset($this->error_msg);

      $objid = (string)$obj['id'];
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.processVisitsBatch";

      $amf->_bodys[0]->_value[1][0]['params'][0][$objid]['NPCEnterAction']['npcBreakDown']['residence'] = $extraVisits;

      if(in_array($obj['className'], array('Hotel', 'Mall', 'SocialBusiness', 'ThemePark')))
         $type = "harvestState";
      elseif ($obj['className'] == "Subway")
		 $type = "customerState";
	  else
         $type = "visits";
      $amf->_bodys[0]->_value[1][0]['params'][0][$objid]['NPCEnterAction']['type'] = $type;
      $amf->_bodys[0]->_value[1][0]['params'][0][$objid]['NPCEnterAction']['count'] = $extraVisits;// the max amount of visitors.
      $amf->_bodys[0]->_value[1][0]['params'][0][$objid]['NPCEnterAction']['operation'] = "process";

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);
      $this->SendMsg($this->irc('cc') . '14(' . $msg . ') Visiting: [' . $obj['itemName'] . "] $extraVisits times.");
      //$this->SendMsg("($msg): Visiting: [" . $obj['itemName'] . "] $extraVisits times. ");
      //$this->Add2Report('processVisits');
   }
   // ==============================================================================
   // Airline / Truck
   // ============================================================================== 
    function ObjectActionImExport($id, $obj, $param, $mode, $operation, $contract, $flag)
   {
      unset($this->error_msg);

      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';


	  //get the correct timers
      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
      $clientTime = microtime(true);
      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "GameMechanicService.performMechanicAction";
      $amf->_bodys[0]->_value[1][0]['params'] = Array();
      $amf->_bodys[0]->_value[1][0]['params'][0] = $id;
      $amf->_bodys[0]->_value[1][0]['params'][1] = $param;
      $amf->_bodys[0]->_value[1][0]['params'][2] = $mode;
	  $amf->_bodys[0]->_value[1][0]['params'][3]['operation'] = $operation;
	  $amf->_bodys[0]->_value[1][0]['params'][3]['contractName'] = $contract;
	  $amf->_bodys[0]->_value[1][0]['params'][3]['clientEnqueueTime'] = microtime(true);


      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);

	  if($operation == "harvest") $this->SendMsg($this->irc('cc') . '2(' . $msg . ')');
      else
      if($operation == "plant") $this->SendMsg($this->irc('cc') . '3(' . $msg . '):' . $obj['itemName'] . ' (ID:' . $obj["id"] . ') send to: ' . $contract . '');
	  else
      if($operation == "clear") $this->SendMsg($this->irc('cc') . '7(' . $msg . ')');
	  
	  
	  $this->CheckDoobers($x);//check for any doobers

	  if($operation == "harvest") $text1 = 'Harvest '.$flag;
	  if($operation == "plant") $text1 = 'Send '.$flag;
	  if($operation == "clear") $text1 = 'Clear '.$flag;
      $this->Add2Report($text1);
      }
   // ==============================================================================
   // Green House ==================================================================
   // ==============================================================================
    function ObjectActionCrop($id, $param, $mode, $contract, $flag, $obj)
   {  
   
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';


	  //get the correct timers
      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
      $clientTime = microtime(true);
      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "GameMechanicService.performMechanicAction";
      $amf->_bodys[0]->_value[1][0]['params'] = Array();
      $amf->_bodys[0]->_value[1][0]['params'][0] = $id;
      $amf->_bodys[0]->_value[1][0]['params'][1] = $param;
      $amf->_bodys[0]->_value[1][0]['params'][2] = $mode;
	  if($param == "greenHouseStorage") 
	  {$amf->_bodys[0]->_value[1][0]['params'][3]['plotname'] = $contract; }
	  else
	  {$item = $amf->_bodys[0]->_value[1][0]['params'][3]['item'] = $contract; }
	  $amf->_bodys[0]->_value[1][0]['params'][3]['clientEnqueueTime'] = microtime(true);
	  $amf->_bodys[0]->_value[1][0]['params'][3]['multiplier'] = '';
      if(($param == "greenHouseHarvest") || ($param == "greenHouseClear"))
	  $amf->_bodys[0]->_value[1][0]['params'][3]['operation'] = 'harvest';


      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);
	  
	  
	  if($param == "greenHouseHarvest") $this->SendMsg($this->irc('cc') . '2(' . $msg . ')');
      else
      if($param  == "greenHouseStorage") $this->SendMsg($this->irc('cc') . '3(' . $msg . '):' . $obj['itemName'] . ' (ID:' . $obj["id"] . ') seed: ' . $contract . '');
	  else
      if($param  == "greenHouseClear") $this->SendMsg($this->irc('cc') . '7(' . $msg . ')');
	  
	  
	  if($param == "greenHouseHarvest") $text1 = 'Harvest '.$flag;
	  if($param == "greenHouseStorage") $text1 = 'Plant '.$flag;
	  if($param == "greenHouseClear") $text1 = 'Clear '.$flag;
      $this->Add2Report($text1);
   }
   // ==============================================================================
   // ------------------------------------------------------------------------------
   // ==============================================================================
   function onCollectDailyBonus($obj)
   {
      $this->SendMsg('Franchise Collect Daily Bonus ' . $obj['name']);
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "FranchiseService.onCollectDailyBonus";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $obj['name'];

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      $x = $this->SendRequest($result);
      $this->Add2Report('Franchise Collect Daily Bonus');
   }
   // ==============================================================================
   //  functionName  String  UserService.onRemoveFromInventory
   function RemoveFromInventory($item, $amount)
   {
      $this->SendMsg('Remove From Inventory: ' . $amount . " " . $item);

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.onRemoveFromInventory";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $item;
      $amf->_bodys[0]->_value[1][0]['params'][1] = $amount;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      $x = $this->SendRequest($result);
      $this->Add2Report('Remove From Inventory');
   }
   // ==============================================================================
   function redeemVisitorHelpAction($objs, $sname)
   {
      $this->SendMsg('[NEIGHBORS] Accepting help from: ' . $sname);

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

	  $i = 0;
	  
      foreach($objs as $obj)

      {
         $item = $this->fobjects["w$obj"];//gets each item quickly

         $this->SendMsg('[NEIGHBORS] Accepting help on ' . " obj=" . $item['itemName'] . " ($obj)");

		 $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);

         $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
         $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
         $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

         $amf->_bodys[0]->_value[1][$i]['sequence'] = $this->GetSequense();;
         $amf->_bodys[0]->_value[1][$i]['functionName'] = "VisitorService.redeemVisitorHelpAction";
         $amf->_bodys[0]->_value[1][$i]['params'][0] = $sname;
         $amf->_bodys[0]->_value[1][$i]['params'][1] = $obj;
         $amf->_bodys[0]->_value[1][$i]['params'][2] = $item['className'];
         $amf->_bodys[0]->_value[1][$i]['params'][3] = $item['itemName'];
         $param4 = "";
         $amf->_bodys[0]->_value[1][$i]['params'][4] = (string)$param4;
         $amf->_bodys[0]->_value[1][$i]['params'][5] = microtime(true);//fix for wonder radius



      //add this line to results that does not give dooberitems via AMF, but streak bonus can be collected.
      //$this->dooberItems +=2;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $this->CheckDoobers($x);
	  $this->streakBonus3();
	  $i++;
   }

      
	  
      $this->Add2Report('Accept Neighbors help');
   }
   // ==============================================================================
   /*function updateEnergy()
      {
      		$this->SendMsg('updateEnergy');
      
      		unset($this->error_msg);
      		$amf = new AMFObject("");
      		$amf->_bodys[0] = new MessageBody();
      		$amf->_bodys[0]->_value[0] = $this->GetAmfHeader();
      
      		$amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      		$amf->_bodys[0]->responseURI = '';
      		$amf->_bodys[0]->_value[2] = 0;
      
      		$amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      		$amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.updateEnergy";
      		$amf->_bodys[0]->_value[1][0]['params'] = Array();
      		$amf->_bodys[0]->_value[2] = 0;
      
      		$serializer = new AMFSerializer();
      		$result = $serializer->serialize($amf);
      		$x = $this->SendRequest($result);
      		$this->Add2Report('updateEnergy');
   }*/
   // ==============================================================================
   function orig_streakBonus($i, $cnt)
   {
      $bonus = round(($this->level * 1.5 * 55) - 1);
      $this->SendMsg('streakBonus ' . $i . '/' . $cnt . ': ' . $bonus);

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.streakBonus";
      $amf->_bodys[0]->_value[1][0]['params'][0]['amount'] = 9;//$bonus; //9;
      $amf->_bodys[0]->_value[1][0]['params'][0]['maxesReached'] = 1;
      $amf->_bodys[0]->_value[2] = 0;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      $x = $this->SendRequest($result);
      $this->Add2Report('streakBonus');
      }
   // ==============================================================================
   function streakBonusCheck()
      {

      $showDooberInLog = true;// Make this false to have less log
      if($showDooberInLog && is_array($this->dooberItem))
      {
         foreach($this->dooberItem as $item=>$amount)          {$this->Add2Report('Bonus: ' . $item);}
         $this->dooberItem = array();
      }
      // check if we can get streakBonus

      //before - [$streakBonus = $this->GetParamByName("steakbonus");]
      //after - [] collecting bonus always til Z* patch it

      // streak bonus is now controled via the settings plugin.
      // $streakBonus = 1; // 0 = Do not collect streakBonus (off, in case Z patch this again)
      // 1 = collect streakBonus every time (default)
      // 2 - 31 = configurable
      // 32 = the normal amount to collect maximum bonus.

      //before - [if($streakBonus == 0 ) return;]
      //after - [] collecting bonus always til Z* patch it

      if($this->dooberItems > $streakBonus)
      {
         $this->streakBonus3();
         $this->dooberItems = 0;
      }
      return;
      }
   // ==============================================================================
   function streakBonus2()     {return;}// place holder to be backward compatible
   function streakBonus3()
      {

      $bonus = round(($this->level * 1.5 * 55) - 1);
      $this->dooberItem['coin'] += $bonus;
      //unset($this->error_msg); //cant unset here
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();
	  
      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;
      
      //Added by Tonycell
      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.streakBonus";
      $amf->_bodys[0]->_value[1][0]['params'] = array();//9;
      $amf->_bodys[0]->_value[1][0]['params'][0]['amount'] = $bonus;//9;
      $amf->_bodys[0]->_value[1][0]['params'][0]['maxesReached'] = 10;
      $amf->_bodys[0]->_value[2] = 0;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $this->CheckServerError($x);

      //the action does not support streakbonus
      //if(isset($this->error_msg))
      //{
      //   $text = "ERROR: This action does not support streakbonus";
      //unset($this->error_msg);
      //}
      //else
      //{
      //   $text = 'streakBonus3: ' . $bonus . ' coins';
      //   $this->Add2Report('streakBonus3');
      //}

      if( ! isset($this->error_msg) || ($this->error_msg == ""))
   {
         $text = 'streakBonus3: ' . $bonus . ' coins';
         $this->Add2Report('streakBonus3');

         $this->SendMsg($this->irc('cc') . '7BONUS: ' . $text);
   }
      //$this->SendMsg("$text" . $obj['itemName'] . ' (id:'.$obj["id"].')'); }
   }
   // ==============================================================================
   function setCityName($name)
   {
      $this->SendMsg('setCityName: ' . $name);
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.setCityName";
      $amf->_bodys[0]->_value[1][0]['params'][0] = 'renameCity';
      $amf->_bodys[0]->_value[1][0]['params'][1] = $name;
      $amf->_bodys[0]->_value[2] = 0;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      $x = $this->SendRequest($result);
      $this->Add2Report('setCityName');
   }
   // ==============================================================================
   function AcceptFranchiseRequest($obj)
   {
      //$this->SendMsg('-> Accepting Franchise: adding ('. $obj['senderID'] .') on Lot:'.$obj['lotId']);

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      //fix by Tonycell
      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);

      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);
      $amf->_bodys[0]->_value[1][0]['params'][0] = (string)$obj['senderID'];
      $amf->_bodys[0]->_value[1][0]['params'][1] = (int)$obj['lotId'];
      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "LotOrderService.acceptOrder";
      $amf->_bodys[0]->_value[2] = 0;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      $x = $this->SendRequest($result);
      $this->Add2Report('Accept Franchise');
   }
   // ==============================================================================
   function updateFranchiseName($fname)
   {
      $this->SendMsg('-> Updating Franchise list: adding (' . $fname . ')');

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "FranchiseService.updateFranchiseName";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $fname;
      $amf->_bodys[0]->_value[1][0]['params'][1] = '';
      $amf->_bodys[0]->_value[2] = 0;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      $x = $this->SendRequest($result);
      $this->Add2Report('Update Franchise');
   }

   // ======================= LotSite build franchise =========================
   function placeOrder($obj)
      {
      $this->SendMsg('# LotId: ' . $obj['lotId']);
      $this->SendMsg('# Place Order: ' . $obj['resourceType'] . ' on: ' . $obj['recipientID']);
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "LotOrderService.placeOrder";
      $amf->_bodys[0]->_value[1][0]['params'][0]['constructionCount'] = 0;
      $amf->_bodys[0]->_value[1][0]['params'][0]['offsetY'] = null;
      $amf->_bodys[0]->_value[1][0]['params'][0]['senderID'] = $this->zyUid;//that is me
      $amf->_bodys[0]->_value[1][0]['params'][0]['lotId'] = $obj['lotId'];
      $amf->_bodys[0]->_value[1][0]['params'][0]['recipientID'] = $obj['recipientID'];
      $amf->_bodys[0]->_value[1][0]['params'][0]['orderResourceName'] = '';
      $amf->_bodys[0]->_value[1][0]['params'][0]['resourceType'] = $obj['resourceType'];
      $amf->_bodys[0]->_value[1][0]['params'][0]['offsetX'] = null;
		
      //	constructionCount  Integer  0
      //	offsetY  Undefined
      //	senderID  String Reference  2222222222
      //	lotId  Integer  118
      //	recipientID  String  20022222222
      //	orderResourceName  String  Kees's Cinema
      //	resourceType  String  bus_movietheater
      //	offsetX  Undefined

      $amf->_bodys[0]->_value[2] = 0;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      $x = $this->SendRequest($result);
      $this->Add2Report('Build Franchise');
      if(isset($this->error_msg))        {$this->ReloadConfig();}
      }
   // ==============================================================================
   function streakBonus($i, $cnt)
      {
      $bonus = round(($this->level * 1.5 * 55) - 1);
      $bonus = round(($this->level * 1.5) - 1);
      //$bonus = 126;
      $bonusM = (8 * $bonus);
      $this->SendMsg('streakBonus (Multi) ' . $i . '/' . $cnt . ': 8*' . $bonus . ' = ' . $bonusM);

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.streakBonus";
      $amf->_bodys[0]->_value[1][0]['params'][0]['amount'] = $bonus;//9;
      $amf->_bodys[0]->_value[1][0]['params'][0]['maxesReached'] = 1;

      $amf->_bodys[0]->_value[1][1]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][1]['functionName'] = "UserService.streakBonus";
      $amf->_bodys[0]->_value[1][1]['params'][0]['amount'] = $bonus;//9;
      $amf->_bodys[0]->_value[1][1]['params'][0]['maxesReached'] = 1;

      $amf->_bodys[0]->_value[1][2]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][2]['functionName'] = "UserService.streakBonus";
      $amf->_bodys[0]->_value[1][2]['params'][0]['amount'] = $bonus;//9;
      $amf->_bodys[0]->_value[1][2]['params'][0]['maxesReached'] = 1;

      $amf->_bodys[0]->_value[1][3]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][3]['functionName'] = "UserService.streakBonus";
      $amf->_bodys[0]->_value[1][3]['params'][0]['amount'] = $bonus;//9;
      $amf->_bodys[0]->_value[1][3]['params'][0]['maxesReached'] = 1;

      $amf->_bodys[0]->_value[1][4]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][4]['functionName'] = "UserService.streakBonus";
      $amf->_bodys[0]->_value[1][4]['params'][0]['amount'] = $bonus;//9;
      $amf->_bodys[0]->_value[1][4]['params'][0]['maxesReached'] = 1;

      $amf->_bodys[0]->_value[1][5]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][5]['functionName'] = "UserService.streakBonus";
      $amf->_bodys[0]->_value[1][5]['params'][0]['amount'] = $bonus;//9;
      $amf->_bodys[0]->_value[1][5]['params'][0]['maxesReached'] = 1;

      $amf->_bodys[0]->_value[1][6]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][6]['functionName'] = "UserService.streakBonus";
      $amf->_bodys[0]->_value[1][6]['params'][0]['amount'] = $bonus;//9;
      $amf->_bodys[0]->_value[1][6]['params'][0]['maxesReached'] = 1;

      $amf->_bodys[0]->_value[1][7]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][7]['functionName'] = "UserService.streakBonus";
      $amf->_bodys[0]->_value[1][7]['params'][0]['amount'] = $bonus;//9;
      $amf->_bodys[0]->_value[1][7]['params'][0]['maxesReached'] = 1;

      $amf->_bodys[0]->_value[2] = 0;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      $x = $this->SendRequest($result);
      $this->Add2Report('streakBonus multi');
      $total = $cnt * $bonusM;
      if(($i + 1) == $cnt)        {$this->SendMsg('streakBonus totaly collected ' . $total);}
   }
   // ------------------------------------------------------------------------------
   function TradeCollection($collectionType, $i, $cnt)
         {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();
      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;
      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "CollectionsService.onTradeIn";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $collectionType;
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      $x = $this->SendRequest($result);
      $this->Add2Report('Trade in collections');
      $this->SendMsg('Trade in ' . $collectionType . ' : ' . $i . '/' . $cnt);
         }

   
   //==============================================================================
   //== Function for Neighbor Plugin
   //== Function to load Neighbors world
   //==============================================================================
   function NLoadWorld($nuid, $name)
   {
      if($nuid == $this->zyUid)        {$this->SendMsg('Continue ');return "";}
      //$this->SendMsg('Load world id: '.$nuid . '  name: ' . $name);
      //$this->statistics['load world'][]=1;
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '/1';

      //fix by Tonycell
      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell
      //1st transaction

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "VisitorService.initialVisit";
      $amf->_bodys[0]->_value[1][0]['params'][0] = "neighborVisit";
      //$amf->_bodys[0]->_value[1][0]['params'][1] = Array();
      $amf->_bodys[0]->_value[1][0]['params'][1]['recipientId'] = $nuid;// who to visit
      $amf->_bodys[0]->_value[1][0]['params'][1]['senderId'] = $this->zyUid;// me $this->zyUid
      //2nd transaction
      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][1]['sequence'] = $this->GetSequense();
      $amf->_bodys[0]->_value[1][1]['functionName'] = "WorldService.loadWorld";
      $amf->_bodys[0]->_value[1][1]['params'][0] = $nuid;// who to visit
      //3rd transaction
      //Temporaly inactive
      /*$amf->_bodys[0]->_value[1][0]['transaction']['canPerform']=true;          //by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);                  //by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);      //by Tonycell
      		$amf->_bodys[0]->_value[1][2]['sequence'] = $this->GetSequense();
      		$amf->_bodys[0]->_value[1][2]['functionName'] = "MissionService.getRandomMission";
      		$amf->_bodys[0]->_value[1][2]['params'][0] = $nuid;*/

      $amf->_bodys[0]->_value[2] = 0;//finish

      //creating the request
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);//sending the request
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);
      //$this->CheckDoobers($x); //dont need check for doober while loading a neighbor city

      //$this->Add2Report('load world');

      return $x;
   }
   //==============================================================================
   //== Function for Neighbor Plugin
   //== Function to do work at the neighbor world.
   //==============================================================================
   function BlessNeighbor(&$fobj, $hostID, $bonus, $ObjState)
   {
      $msg = '[NEIGHBORS] Bless neighbor ';
      if((array_key_exists('mechanicData', $fobj)) && ($fobj['mechanicData']['socialInventory']['heart'] == 1)) //<---- heart logo add by dada79
      {

         $msg .= $this->irc('cc') . '4(';
         $msg .= $this->irc('ff') . '7,5' . chr(169) . $this->irc('ff') . '10,5';
         $msg .= $this->irc('c');
         $msg .= $this->irc('cc') . '4) ';
         $msg .= $this->irc('c');

      }
      if(array_key_exists('className', $fobj))        {$msg .= '(' . $fobj['className'] . ') ';}
      if(array_key_exists('itemName', $fobj))        {$msg .= '(' . $fobj['itemName'] . ') ';}
      if(array_key_exists('contractName', $fobj))        {$msg .= '(' . $fobj['contractName'] . ') ';}
      if(array_key_exists('targetBuildingName', $fobj))        {$msg .= '(' . $fobj['targetBuildingName'] . ') ';}
      $this->SendMsg($msg . ', id : ' . $fobj['id']);

      switch($fobj['className'])
      {
         case "Residence";$action = "residenceCollectRent";break 1;
         case "Business";case "Attraction";case "Mall";case "Mall2";case "Airplane";$action = "businessSendTour";break 1;
         case "Plot";
         {
            switch($fobj['state'])
            {
               case "grown";$action = "plotHarvest";break 1;
               case "planted";$action = "plotWater";break 1;
               case "withered";$action = "plotRevive";break 1;//fixed by Tonycell
            }
         }
         case "Ship";
         {
            switch($fobj['state'])//by dada79
            {
               case "grown";$action = "shipHarvest";break 1;
               case "planted";$action = "shipWater";break 1;
               case "withered";$action = "shipRevive";break 1;
            }
         }
         case "ConstructionSite";$action = "constructionSiteConstruct";break 1;
         case "Wilderness";$action = "wildernessClear";break 1;
      }

      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';

      //get the correct timers
      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
      $clientTime = microtime(true);
      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell
	  
	  $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "VisitorService.help";
      $amf->_bodys[0]->_value[1][0]['params'][0] = "visitorHelp";
      $amf->_bodys[0]->_value[1][0]['params'][1] = $action;
      //$amf->_bodys[0]->_value[1][0]['params'][2] = Array();
      $amf->_bodys[0]->_value[1][0]['params'][2]['gaveMastery'] = Array();//added by Tonycell
      $amf->_bodys[0]->_value[1][0]['params'][2]['helpTargets'] = Array();
      $amf->_bodys[0]->_value[1][0]['params'][2]['helpTargets'][0] = (int)$fobj['id'];
      $amf->_bodys[0]->_value[1][0]['params'][2]['orderState'] = "pending";
      $amf->_bodys[0]->_value[1][0]['params'][2]['orderType'] = "order_visitor_help";
      $amf->_bodys[0]->_value[1][0]['params'][2]['recipientID'] = $fobj['VisitorId'];
      $amf->_bodys[0]->_value[1][0]['params'][2]['senderID'] = $this->zyUid;
      $amf->_bodys[0]->_value[1][0]['params'][2]['status'] = null;//modified to null - by Tonycell
      //$amf->_bodys[0]->_value[1][0]['params'][2]['timeSent']	   = microtime(1) * 1000;
      $amf->_bodys[0]->_value[1][0]['params'][2]['timeSent'] = $clientTime;//to work with new Wonder

      $amf->_bodys[0]->_value[1][0]['params'][2]['transmissionStatus'] = "sent";//fixed (was "send" before) - by Tonycell

      //added 2nd transaction added by Tonycell
      //in case of Attraction or Malls
      switch($fobj['className'])
      {case "Attraction";case "Mall";case "Mall2";
         {
            //$amf->_bodys[0]->_value[1][1]['transaction']['canPerform']=true;
            //$amf->_bodys[0]->_value[1][1]['stamp']         = floatval($stamp);
            //$amf->_bodys[0]->_value[1][1]['enqueueTime']   = floatval($enqueueTime);
            $amf->_bodys[0]->_value[1][1]['functionName'] = "GameMechanicService.performNeighborMechanicAction";
            $amf->_bodys[0]->_value[1][1]['sequence'] = $this->GetSequense();
		    $amf->_bodys[0]->_value[1][1]['footer'] = $this->getQuestsFooter();
            $amf->_bodys[0]->_value[1][1]['params'] = Array();
            $amf->_bodys[0]->_value[1][1]['params'][0] = (int)$fobj['id'];
            $amf->_bodys[0]->_value[1][1]['params'][1] = "visitors";
            $amf->_bodys[0]->_value[1][1]['params'][2] = "GMVisit";
            $amf->_bodys[0]->_value[1][1]['params'][3]['neighbor'] = (string)$fobj['VisitorId'];
            $amf->_bodys[0]->_value[1][1]['params'][3]['clientEnqueueTime'] = $clientTime;

         }
      }
	  
	  //added 3nd transaction added by BQ
      //in case of Airplane
      switch($fobj['className'])
      {case "Airplane";
	  
	  //if($fobj['state'] == "planted")  $state = "grown";  // harvest
	  //if($fobj['state'] == "planted")  $state = "planted";  // speed up
	  //if($fobj['state'] == "withered")  $state = "withered";
	  
         {
            //$amf->_bodys[0]->_value[1][1]['transaction']['canPerform']=true;
            //$amf->_bodys[0]->_value[1][1]['stamp']         = floatval($stamp);
            //$amf->_bodys[0]->_value[1][1]['enqueueTime']   = floatval($enqueueTime);
            $amf->_bodys[0]->_value[1][1]['functionName'] = "GameMechanicService.performNeighborMechanicAction";
            $amf->_bodys[0]->_value[1][1]['sequence'] = $this->GetSequense();
		    $amf->_bodys[0]->_value[1][1]['footer'] = $this->getQuestsFooter();
            $amf->_bodys[0]->_value[1][1]['params'] = Array();
            $amf->_bodys[0]->_value[1][1]['params'][0] = (int)$fobj['id'];
            $amf->_bodys[0]->_value[1][1]['params'][1] = "visitors";
            $amf->_bodys[0]->_value[1][1]['params'][2] = "GMVisit";
            $amf->_bodys[0]->_value[1][1]['params'][3]['neighbor'] = (string)$fobj['VisitorId'];
			$amf->_bodys[0]->_value[1][1]['params'][3]['operation'] = "visitHelp";
            $amf->_bodys[0]->_value[1][1]['params'][3]['clientEnqueueTime'] = $clientTime;
			$amf->_bodys[0]->_value[1][1]['params'][3]['previousState'] = $ObjState; // varies by state
         }
      }

      $amf->_bodys[0]->_value[2] = 0;//finish

      //add this line to results that does not give dooberitems via AMF, but streak bonus can be collected.
      //$this->dooberItems +=2;

      //creating the request
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      //if (in_array($fobj['className'],array('Attraction','Mall', 'Mall2')))
      //{
      //  $x = $this->SendRequest($result); //sending the request
      // }
      $x = $this->SendRequest($result);//sending the request
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      //$amf = new AMFObject($x);
      //$deserializer = new AMFDeserializer($amf->rawData);
      //$deserializer->deserialize($amf);
      //$bod = new MessageBody();
      //$bod = $amf->_bodys[0];
      $bod = $x->_bodys[0];

      $msg = '(' . $bod->_value['data'][0]['data']['result'] . ')';

      if(in_array($fobj['className'], array('Attraction', 'Mall', 'Mall2')))
      {$msg = $msg . ' (' . $bod->_value['data'][1]['data']['result'] . ')';}

      $this->SendMsg('[NEIGHBORS] ##: ' . $msg);

      if(isset($this->error_msg))
      {
         $this->SendMsg('[NEIGHBORS] Error: ' . $this->error_msg);
         unset($this->error_msg);
      }

      $this->CheckDoobers($x);//check for doobers
      //Attraction & Malls does not support streakbonus
      if( ! in_array($fobj['className'], array('Attraction', 'Mall', 'Mall2')) && ($bonus == 1))
      {
         $this->streakBonus3();
      }
   }
   //==============================================================================
   //== Function for functionName  UserService.streamPublish
   //== Function to publish to facebook wall.
   //==============================================================================
   function streamPublish($feed)
   {
      $this->SendMsg('streamPublish ' . $feed);

      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;//by Tonycell
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);//by Tonycell
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);//by Tonycell

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.streamPublish";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $feed;// example: energy_feed  wishlist_request qm_holiday_snow_snowball
      $amf->_bodys[0]->_value[1][0]['params'][1] = (object)"";
      $amf->_bodys[0]->_value[1][0]['params'][2] = $this->zyUid;
      //$amf->_bodys[0]->_value[1][0]['params'][3] = null;
      //$amf->_bodys[0]->_value[1][0]['params'][4] = null;
      //$amf->_bodys[0]->_value[1][0]['params'][5] = (boolean)false;
      //$amf->_bodys[0]->_value[1][0]['params'][6] = null;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $this->Add2Report('Publish Requests');

      return $x;
   }
   //==============================================================================
   // campaign_payer -> Added by Tonycell
   // ------------------------------------
   // $bod->_value['data'][0]['data']['inactiveNeighbors'] <- avaliable only for this list
   // still not enabled by Z* (07.10.2011)
   //==============================================================================
   function CampaignPayer()
   {
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $this->GetTimers($stamp, $enqueueTime, $clientEnqueueTime);
      $amf->_bodys[0]->_value[1][0]['transaction']['canPerform'] = true;
      $amf->_bodys[0]->_value[1][0]['stamp'] = floatval($stamp);
      $amf->_bodys[0]->_value[1][0]['enqueueTime'] = floatval($enqueueTime);

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.superStreamPublish";
      $amf->_bodys[0]->_value[1][0]['params'][0] = "campaign_payer";
      $amf->_bodys[0]->_value[1][0]['params'][1]['friendFirst'] = "No Name";//replace with neighbor first name
      $amf->_bodys[0]->_value[1][0]['params'][1]['user'] = (object)"";
      $amf->_bodys[0]->_value[1][0]['params'][1]['numberCash'] = "10";//amount of cash
      $amf->_bodys[0]->_value[1][0]['params'][2] = "12345678901";//neighbor id
      $amf->_bodys[0]->_value[1][0]['params'][3] = null;
      $amf->_bodys[0]->_value[1][0]['params'][4] = null;
      $amf->_bodys[0]->_value[1][0]['params'][5] = (string)"";

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);
      //var_dump($x);

      $this->Add2Report('Campaign Request');

      return $x;
   }
   //==============================================================================
   //== Function for Neighbor Plugin
   //== Function to load Neighbors world in details (neighbors)
   //==============================================================================
   function getRandomMission($nuid)
   {
      //$this->SendMsg('Still looking to find energy for you.... ' );
      //$this->statistics['load world'][]=1;
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '/1';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
      $amf->_bodys[0]->_value[1][0]['params'][0] = $nuid;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "MissionService.getRandomMission";

      //$amf->_bodys[0]->_value[1][1]['sequence'] = $this->GetSequense()
      //$amf->_bodys[0]->_value[1][1]['functionName'] = "UserService.updateEnergy";
      //$amf->_bodys[0]->_value[1][1]['params'] = array();

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      //$this->Add2Report('load world');

      return $x;
   }
   //==============================================================================
   //== Function for SpecialItem			  by fortunes
   //== Function to Accept Orders for empty Lot
   //==============================================================================
   function SpecialItem($resourceType, $lotID, $name)
   {
      $this->SendMsg('SpecialItem starting...');
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();
      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;
      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "LotOrderService.acceptOrder";
      $amf->_bodys[0]->_value[1][0]['params'][0]['offsetX'] = '0';
      $amf->_bodys[0]->_value[1][0]['params'][0]['offsetY'] = '0';
      $amf->_bodys[0]->_value[1][0]['params'][0]['resourceType'] = $resourceType;
      $amf->_bodys[0]->_value[1][0]['params'][0]['senderID'] = -1;//$this->zyUid;
      $amf->_bodys[0]->_value[1][0]['params'][0]['recipientID'] = $this->zyUid;
      $amf->_bodys[0]->_value[1][0]['params'][0]['orderResouceName'] = $name;
      $amf->_bodys[0]->_value[1][0]['params'][0]['lotId'] = $lotID;
      $amf->_bodys[0]->_value[1][0]['params'][0]['constructionCount'] = '0';
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      $x = $this->SendRequest($result);
      $aa = array('bus_', 'res_', 'mun_', '_');
      $item = str_replace($aa, " ", $resourceType);
      $this->SendMsg("place special item " . $item);
      $this->Add2Report('SpecialItem');
   }
   // ------------------------------------------------------------------------------
   function NPostInit()
   {
      $this->SendMsg('PostInit');
      //SendMsg('PostInit');

      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '/1';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "UserService.initUser";
      $amf->_bodys[0]->_value[1][0]['params'][0] = "name";// $this->zyUid;	   // me

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      return $x;
   }
   //==============================================================================
   //== Function for Train Plugin
   //== Function to Send train
   // ==============================================================================
   function sendTrain($mission)
   {
      $this->syncTrain();
      sleep(5);

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "TrainService.sendTrain";
      $amf->_bodys[0]->_value[1][0]['params'][0]['timeSent'] = time();
      $amf->_bodys[0]->_value[1][0]['params'][0]['trainName'] = $mission;
      $amf->_bodys[0]->_value[1][0]['params'][0]['commodityName'] = "goods";

      if(substr_count($mission, "buy") > 0)
         $operation = 'buy';
      else
         $operation = 'sell';
      $amf->_bodys[0]->_value[1][0]['params'][0]['operation'] = $operation;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $this->Add2Report('TrainSend');
   }
   // ==============================================================================
   function syncTrain()
   {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "WorkerService.syncWorkers";
      $amf->_bodys[0]->_value[1][0]['params'][0] = "trains";

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);
   }
   // ==============================================================================
   function receiveTrain($trainWork)
   {
      $this->syncTrain();
      sleep(5);

      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "TrainService.acceptTrain";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $trainWork;

      //add this line to results that does not give dooberitems via AMF, but streak bonus can be collected.
      //$this->dooberItems +=2;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);
	  
      //$this->streakBonus3();  //moved to the plugin directly as an option
	  
      $this->Add2Report('TrainReceive');
   }
   // ==============================================================================
   //  ================================================
   //  ==		   Coin2 Function by fortunes	   ==
   //  ================================================
   function CoinPlaceLot($coin_array)
   {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();
      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '/';
      $amf->_bodys[0]->_value[2] = 0;
      $msg = "Coin : Place lot ";
      $id = 63000;
      $i = 0;
      foreach($coin_array as $obj)
      {
         $tmp = explode("|", $obj);
         $xx = trim($tmp[1]);
         $yy = trim($tmp[2]);
         $amf->_bodys[0]->_value[1][$i]['sequence'] = $this->GetSequense();
         $amf->_bodys[0]->_value[1][$i]['functionName'] = "WorldService.performAction";
         $amf->_bodys[0]->_value[1][$i]['params'][0] = "place";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['itemName'] = "biz_lotsite_4x4";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['state'] = "static";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['tempId'] = "-1";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['components'] = "";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['id'] = $id;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['direction'] = "1";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['position']['x'] = $xx;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['position']['y'] = $yy;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['position']['z'] = "0";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['className'] = "LotSite";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['deleted'] = "false";
         $amf->_bodys[0]->_value[1][$i]['params'][2] = Array();
         $amf->_bodys[0]->_value[1][$i]['params'][2][0]['mapOwner'] = $this->zyUid;
         $amf->_bodys[0]->_value[1][$i]['params'][2][0]['energyCost'] = "0";
         $amf->_bodys[0]->_value[1][$i]['params'][2][0]['itemOwner'] = $this->zyUid;
         $id++;
         $i++;
         $msg = $msg . "(" . $xx . "," . $yy . ") ";
      }
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      //		$this->SendMsg($msg);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      return $x;
   }

   function CoinPlaceTower($coin_array)
   {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();
      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;
      $msg = "Coin : Place Tower ";
      $i = 0;
      foreach($coin_array as $obj)
      {
         $tmp = explode("|", $obj);
         $id = trim($tmp[0]);
         $amf->_bodys[0]->_value[1][$i]['sequence'] = $this->GetSequense();
         $amf->_bodys[0]->_value[1][$i]['functionName'] = "LotOrderService.acceptOrder";
         $amf->_bodys[0]->_value[1][$i]['params'][0]['offsetX'] = "0";
         $amf->_bodys[0]->_value[1][$i]['params'][0]['offsetY'] = "0";
         $amf->_bodys[0]->_value[1][$i]['params'][0]['resourceType'] = "lm_pearltower";
         $amf->_bodys[0]->_value[1][$i]['params'][0]['senderID'] = $this->zyUid;//"31226733682" ;
         $amf->_bodys[0]->_value[1][$i]['params'][0]['recipientID'] = $this->zyUid;
         $amf->_bodys[0]->_value[1][$i]['params'][0]['orderResouceName'] = "Pearl Tower";
         $amf->_bodys[0]->_value[1][$i]['params'][0]['lotId'] = $id;
         $amf->_bodys[0]->_value[1][$i]['params'][0]['constructionCount'] = "0";
         $i++;
         $msg = $msg . "(" . $id . ") ";
      }
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      //		  $this->SendMsg($msg) ;

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      return $x;
   }

   function CoinSellTower($coin_array, $time)
   {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();
      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;
      $msg = "Coin : Sell Tower ";
      $i = 0;
      foreach($coin_array as $obj)
      {
         $tmp = explode("|", $obj);
         $id = trim($tmp[0]);
         $xx = trim($tmp[1]);
         $yy = trim($tmp[2]);
         $amf->_bodys[0]->_value[1][$i]['sequence'] = $this->GetSequense();
         $amf->_bodys[0]->_value[1][$i]['functionName'] = "WorldService.performAction";
         $amf->_bodys[0]->_value[1][$i]['params'][0] = "sell";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['direction'] = 1;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['className'] = "Landmark";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['id'] = $id;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['itemName'] = "lm_pearltower";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['tempId'] = "NaN";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['plantTime'] = $time;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['buildTime'] = $time;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['position']['x'] = $xx;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['position']['y'] = $yy;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['position']['z'] = 0;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['component'] = "";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['deleted'] = "false";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['state'] = "planted";
         $amf->_bodys[0]->_value[1][$i]['params'][2] = Array();
         $i++;
         $msg = $msg . "(" . $xx . "," . $yy . ") ";
      }
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);
      //		$this->SendMsg($msg);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      return $x;
   }

   function CoinSellLot($coin_array)
   {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();
      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;
      $i = 0;
      foreach($coin_array as $obj)
      {
         $tmp = explode("|", $obj);
         $id = trim($tmp[0]);
         $xx = trim($tmp[1]);
         $yy = trim($tmp[2]);
         $amf->_bodys[0]->_value[1][$i]['sequence'] = $this->GetSequense();
         $amf->_bodys[0]->_value[1][$i]['functionName'] = "WorldService.performAction";
         $amf->_bodys[0]->_value[1][$i]['params'][0] = "sell";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['direction'] = 1;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['className'] = "LotSite";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['id'] = $id;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['itemName'] = "biz_lotsite_4x4";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['tempId'] = -1;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['position']['x'] = $xx;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['position']['y'] = $yy;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['position']['z'] = 0;
         $amf->_bodys[0]->_value[1][$i]['params'][1]['component'] = "";
         $amf->_bodys[0]->_value[1][$i]['params'][1]['deleted'] = "false";
         $amf->_bodys[0]->_value[1][$i]['params'][2] = Array();
         $i++;
      }
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      return $x;
   }
   // ==============================================================================
   
   // added by phreaker 15-03-2011
/*
   function CaptureBandit($name)
   {
      $this->SendMsg('Capturing Bandits: ' . $name);
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;
      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();;
      $amf->_bodys[0]->_value[1][0]['functionName'] = "BanditService.captureBandit";
      $amf->_bodys[0]->_value[1][0]['params'][0] = $this->BanditInfo;
      $amf->_bodys[0]->_value[1][0]['params'][1][0] = $this->Bandit;
      $amf->_bodys[0]->_value[2] = 0;

      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $this->Add2Report('CaptureBandits');
   }
*/
   
   // ==============================================================================
   // 13.10.2011
   // Redesigned by Tonycell
   function Try2CaptureOneBandit($idx)
   {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      //$amf->_bodys[0]->_value[1][0]['functionName'] = "BanditService.captureBandit";
      $amf->_bodys[0]->_value[1][0]['functionName'] = "PreyService.capturePrey";
	  $amf->_bodys[0]->_value[1][0]['footer'] = (string)"";
      $amf->_bodys[0]->_value[1][0]['params'] = array();
      $amf->_bodys[0]->_value[1][0]['params'][0] = "copsNBandits";
      $amf->_bodys[0]->_value[1][0]['params'][1] = intval($idx);//<== type of bandit
      $amf->_bodys[0]->_value[1][0]['params'][2] = array();//make a clear array


      //Added by Tonycell
      $copsRequired = $this->banditlist[$idx];//total cops required

      //find patrolling police officers, if there exist
      //if none then false
      $allcops = array();
      $allcops = $this->arPoliceOfficer;
      $cntCops = count($allcops);

      //not a lvl7 police station
      if( ! $this->policelvl7)
      {
         $this->SendMsg("[BUILDINGS-Bandits] Trying to capture Bandit($idx)");
         echo "[BUILDINGS-Bandits] Bandit($idx) requires $copsRequired cops, you have $cntCops\n";
         if($cntCops >= $copsRequired)
         {
            $i = 0;
            foreach($allcops as $keycop=>$cop)
            {
               if($cop >= 0)
               {
                  $amf->_bodys[0]->_value[1][0]['params'][2][$i] = (int)$cop;//<=== police officers
                  $i++;
                  unset($allcops[$keycop]);//remove the police from the avaliable list
				  if ($i == $copsRequired) {break 1;}
               }
            }
            $this->arPoliceOfficer = $allcops;//save
         }
         else
         {
            $this->SendMsg('[BUILDINGS-Bandits] Error: Not enough cops, need ' . $copsRequired);
            return false;
         }
      }
      else
      {
         $this->SendMsg('[BUILDINGS-Bandits] Trying to capture Bandit(' . $idx . ')');
      }

      $amf->_bodys[0]->_value[2] = 0;
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);
      $this->SendMsg('[BUILDINGS-Bandits] ' . $msg);

      $this->Add2Report('CaptureBandits');

      return true;
   }
   // ==============================================================================
      function Try2CaptureOneBanditDT($idx)
   {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      //$amf->_bodys[0]->_value[1][0]['functionName'] = "BanditService.captureBandit";
      $amf->_bodys[0]->_value[1][0]['functionName'] = "PreyService.capturePrey";
	  $amf->_bodys[0]->_value[1][0]['footer'] = (string)"";
      $amf->_bodys[0]->_value[1][0]['params'] = array();
      $amf->_bodys[0]->_value[1][0]['params'][0] = "downtownpolice";
      $amf->_bodys[0]->_value[1][0]['params'][1] = intval($idx);//<== type of bandit
      $amf->_bodys[0]->_value[1][0]['params'][2] = array();//make a clear array


      //Added by Tonycell
      $copsRequired = $this->banditlistDT[$idx];//total cops required

      //find patrolling police officers, if there exist
      //if none then false
      $allcops = array();
      $allcops = $this->arPoliceOfficerDT;
      $cntCops = count($allcops);

      //not a lvl7 police station
      //if( ! $this->policelvl7)
      //{
         $this->SendMsg("[BUILDINGS-BanditsDT] Trying to capture Bandit($idx)");
         echo "[BUILDINGS-BanditsDT] Bandit($idx) requires $copsRequired cops, you have $cntCops\n";
         if($cntCops >= $copsRequired)
         {
            $i = 0;
            foreach($allcops as $keycop=>$cop)
            {
               if($cop >= 0)
               {
                  $amf->_bodys[0]->_value[1][0]['params'][2][$i] = (int)$cop;//<=== police officers
                  $i++;
                  unset($allcops[$keycop]);//remove the police from the avaliable list
				  if ($i == $copsRequired) {break 1;}
               }
            }
            $this->arPoliceOfficerDT = $allcops;//save
         }
         else
         {
            $this->SendMsg('[BUILDINGS-BanditsDT] Error: Not enough cops, need ' . $copsRequired);
            return false;
         }
      //}
      //else
      //{
         //$this->SendMsg('[BUILDINGS-Bandits] Trying to capture Bandit(' . $idx . ')');
      //}

      $amf->_bodys[0]->_value[2] = 0;
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);
      $this->SendMsg('[BUILDINGS-BanditsDT] ' . $msg);

      $this->Add2Report('CaptureBanditsDT');

      return true;
   }
   // ==============================================================================
   function Try2CaptureOneDoggie($idx)
   {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      //$amf->_bodys[0]->_value[1][0]['functionName'] = "BanditService.captureBandit";
      $amf->_bodys[0]->_value[1][0]['functionName'] = "PreyService.capturePrey";
	  $amf->_bodys[0]->_value[1][0]['footer'] = (string)"";
      $amf->_bodys[0]->_value[1][0]['params'] = array();
      $amf->_bodys[0]->_value[1][0]['params'][0] = "animalRescue";
      $amf->_bodys[0]->_value[1][0]['params'][1] = intval($idx);//<== type of doggie
      $amf->_bodys[0]->_value[1][0]['params'][2] = array();//make a clear array


      //Added by Tonycell
      $copsRequired = $this->dogList[$idx];//total lovers required

      //find patrolling police officers, if there exist
      //if none then false
      $allcops = array();
      $allcops = $this->dogOfficers;
      $cntCops = count($allcops);

      //not a lvl7 police station
      //      if( ! $this->policelvl7)
      //      {
      $this->SendMsg("[BUILDINGS-Doggies] Trying to capture Doggie($idx)");
      $this->SendMsg("[BUILDINGS-Doggies] Doggie($idx) requires $copsRequired Lovers, you have $cntCops");
      if($cntCops >= $copsRequired)
      {
         $i = 0;
         foreach($allcops as $keycop=>$cop)
         {
            if($cop >= 0)
            {
               $amf->_bodys[0]->_value[1][0]['params'][2][$i] = (int)$cop;//<=== doggie lovers
               $i++;
               unset($allcops[$keycop]);//remove the Lover from the avaliable list
               if ($i == $copsRequired){break 1;}
            }
         }
         $this->dogOfficers = $allcops;//save
      }
      else
      {
         $this->SendMsg('[BUILDINGS-Doggies] Error: Not enough Lovers, need ' . $copsRequired);
         $this->sequense -= 1;
         return false;
      }
      //      }
      //      else
      //      {
      //         $this->SendMsg('[BUILDINGS-Doggies] Trying to capture Doggie(' . $idx . ')');
      //      }

      $amf->_bodys[0]->_value[2] = 0;
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);

      $msg = $this->CheckResponse($x);
      $this->SendMsg('[BUILDINGS-Doggies] ' . $msg);

      $this->Add2Report('CaptureDoggies');

      return true;
   }
 // ==============================================================================
 	function Try2CaptureCar($carIdx, $carCoins)
   {
      unset($this->error_msg);
      $amf = new AMFObject("");
      $amf->_bodys[0] = new MessageBody();
      $amf->_bodys[0]->_value[0] = $this->GetAmfHeader();

      $amf->_bodys[0]->targetURI = 'BaseService.dispatchBatch';
      $amf->_bodys[0]->responseURI = '';
      $amf->_bodys[0]->_value[2] = 0;

      $amf->_bodys[0]->_value[1][0]['sequence'] = $this->GetSequense();
	  $amf->_bodys[0]->_value[1][0]['footer'] = $this->getQuestsFooter();
      $amf->_bodys[0]->_value[1][0]['functionName'] = "CarService.harvestCar";
      $amf->_bodys[0]->_value[1][0]['params'] = array();
      $amf->_bodys[0]->_value[1][0]['params'][0] = $carIdx;
      $amf->_bodys[0]->_value[1][0]['params'][1] = $carCoins;
      
      
      $this->SendMsg("[BUILDINGS-Cars] Trying to collect Car($carIdx)");

      $amf->_bodys[0]->_value[2] = 0;
      $serializer = new AMFSerializer();
      $result = $serializer->serialize($amf);

      $x = $this->SendRequest($result);
      $x = $this->Deserialize($x);
      $this->CheckServerError($x);
		
      file_put_contents("tmp_dir/carlog.txt", print_r($x,true), FILE_APPEND);
      
      $msg = $this->CheckResponse($x);
      $this->SendMsg('[BUILDINGS-Cars] ' . $msg);

      $this->Add2Report('Cars');

      return true;
   }
   
   function getQuestsFooter()
   {
   	$retAr = array();
   	foreach($this->arQuests as $q)
   		$retAr[] = $q["name"];
   		
   	return json_encode(array("quests"=>$retAr));
   }
   
}

?>